1

I want to write some lines of commands to a file, but some commands written in $(...) being evaluated. I want $(...) this to preserve.

I have tried following:

cat > .git/hooks/pre-commit << EOM
#Colors
RED='\033[0;31m'
NC='\033[0m' # No Color

# Javascript unit tests 
res=$(script -q /dev/null ./tests/hooks/non-ui-test-hook )
RESULT=$?
[ $RESULT -ne 0 ] && echo -e "$res" && exit 1
echo -e "All test cases passed.\n"
exit 0
EOM

It writes in file following content:

#Colors
RED='\033[0;31m'
NC='\033[0m' # No Color

# Javascript unit tests
res=Warning: Could not find any test files matching pattern: test
No test files found
RESULT=1
[  -ne 0 ] && echo -e "" && exit 1
echo -e "All test cases passed.\n"
exit 0

How can i preserve $(...) in output file?

  • What do you mean preserve it? What's your desired output? – Zanna Jun 6 '17 at 13:41
4

You can alternatively escape $:

\$(...)
\$

in your code:

cat > .git/hooks/pre-commit << EOM
#Colors
RED='\033[0;31m'
NC='\033[0m' # No Color

# Javascript unit tests 
res=\$(script -q /dev/null ./tests/hooks/non-ui-test-hook )
RESULT=\$?
[ $RESULT -ne 0 ] && echo -e "$res" && exit 1
echo -e "All test cases passed.\n"
exit 0
EOM
  • it solved the issue, thanks. I have one more issue. I am using res=$(script -q /dev/null mocha $(find "tests/non-ui" -name "*.js")) command to run my test cases and get command output but it is returning only last line of test case result. – chandil03 Jun 8 '17 at 5:27
  • Your question is a little bit fuzzy to me :) ask it as another question provide more details the output you desire and the output you get so more people can help you... ;) – Ravexina Jun 8 '17 at 8:34
  • Escape AND quote the variables. res="\$(script -q /dev/null ./tests/hooks/non-ui-test-hook )" – Sergiy Kolodyazhnyy Jun 8 '17 at 15:31
2

Quote the end indicator of the here document, EOM in your case:

cat > .git/hooks/pre-commit << 'EOM'
...
...
EOM

Escaping using double quotes or backslash would do too:

cat > .git/hooks/pre-commit << "EOM"
...
...
EOM

Or

cat > .git/hooks/pre-commit << \EOM
...
...
EOM

You might have not noticed but RESULT=$? also got expanded to RESULT=1 i.e. the exit status of script... inside the command substitution.

Just for the sake of completeness, if you want some expansion to happen but not others, you need to follow what you have currently and escape the ones you want to preserve with typical escaping methods.

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.