Using grep inside shell script gives file not found error

23,761

You need to use command substitution:

#!/usr/bin/env bash

test=$(grep 'foo' "$1")
echo "$test"

Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed like this:

$(command)

or like this using backticks:

`command`

Bash performs the expansion by executing COMMAND and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

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

$(command $(command))

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

Share:
23,761
Bonz0
Author by

Bonz0

Updated on October 19, 2020

Comments

  • Bonz0
    Bonz0 over 3 years

    I cannot believe I've spent 1.5 hours on something as trivial as this. I'm writing a very simple shell script which greps a file, stores the output in a variable, and echos the variable to STDOUT.

    I have checked the grep command with the regex on the command line, and it works fine. But for some reason, the grep command doesn't work inside the shell script.

    Here is the shell script I wrote up:

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

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

    • I have already used chmod and made the script executable.
    • I have checked that the PATH variable has /bin in it.
    • Verified that echo $SHELL gives /bin/bash
    • In my desperation, I have tried all combinations of:
      • tt=grep 'test' "$1"
      • echo ${tt}
      • Not using the command line argument at all, and hardcoding the name of the file tt=grep 'test' testingFile
    • I found this: grep fails inside bash script but works on command line, and even used dos2unix to remove any possible carriage returns.
    • Also, when I try to use any of the grep options, like: tt=grep -oE 'test' testingFile, I get an error saying: ./out.sh: line 3: -oE: command not found.
    • This is crazy.
  • Bonz0
    Bonz0 over 10 years
    Wow. Thank you so much. Just curious, is this different for zsh?