Using grep inside a shell script gives a file error not found

I can’t believe that I spent 1.5 hours on something as trivial as this. I am writing a very simple shell script that smooths a file, stores the result in a variable, and translates the variable into STDOUT.

I checked the grep command with regex on the command line and it works fine. But for some reason, the grep command does not work inside the shell script.

Here is the shell script I wrote:

#!/bin/bash tt=grep 'test' $1 echo $tt 

I accomplished this with the following command: ./myScript.sh testingFile . It just prints an empty line.

  • I already used chmod and executed the script executable.
  • I checked that the PATH variable has /bin in it.
  • Checked that echo $SHELL gives /bin/bash
  • In desperation, I tried all the combinations:
    • tt=grep 'test' "$1"
    • echo ${tt}
    • Do not use command line argument at all and hardcoding file name tt=grep 'test' testingFile
  • I found this: grep crashes inside the bash script, but works on the command line and even used dos2unix to remove any possible carriage returns.
  • Also, when I try to use any of the grep options, for example: tt=grep -oE 'test' testingFile , I get an error: ./out.sh: line 3: -oE: command not found .
  • This is madness.
+8
bash shell grep ubuntu
source share
1 answer

You need to use command substitution:

 #!/usr/bin/env bash test=$(grep 'foo' "$1") echo "$test" 

Team substitution allows you to display a command to replace the command itself. Command substitution occurs when a command is enclosed in the following command:

 $(command) 

or so using backlinks:

 `command` 

Bash performs the extension by executing the COMMAND command and replacing command substitution with the standard command output, removing any trailing lines. Inline newlines are not deleted, but they can be deleted during word splitting.

The $() version is usually preferable because it allows nesting:

 $(command $(command)) 

For more information, read the command substitution section in man bash .

+13
source share

All Articles