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


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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.