In bash, I'm trying to grep a file for a line beginning with a \, and return the result using backticks.

For example:

echo \\Hello > myFile
out=`cat myFile | grep '^\\Hello'`
echo $out

returns nothing, even though

cat myFile | grep '^\\Hello'

returns, as epected.


This seems extremely odd shell behavior. In particular, the anologous command sequence in tcsh does what one would expect:

set out=`cat myFile | grep '^\\Hello'`; echo $out



Could somebody explain what's going on please? Thanks

1 Answer 1


Read http://mywiki.wooledge.org/BashFAQ/082 and especially

Backslashes inside backticks are handled in a non-obvious manner



is the legacy syntax required by only the very oldest of non-POSIX-compatible bourne-shells. There are several reasons to always prefer the $(...) syntax, so :

echo \\Hello > myFile

and instead of

out=$(cat myFile | grep '^\\Hello')

simplify it a bit :

out=$(grep '^\\Hello' myFile)


echo $out

And "Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes , http://mywiki.wooledge.org/Arguments and http://wiki.bash-hackers.org/syntax/words .

So finally :

echo \\Hello > myFile
out="$(grep '^\\Hello' myFile)"
echo "$out"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .