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.
/bin
in it.echo $SHELL
gives /bin/bash
tt=grep 'test' "$1"
echo ${tt}
tt=grep 'test' testingFile
dos2unix
to remove any possible carriage returns.tt=grep -oE 'test' testingFile
, I get an error saying: ./out.sh: line 3: -oE: command not found
.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With