Home > Software design >  How to avoid the command execution when appending lines to a file
How to avoid the command execution when appending lines to a file

Time:11-27

I'm trying to save the content of script into a file using command line, but I noticed that when the tee command detects linux commands such as $(/usr/bin/id -u), it execute the commands rather than saving the lines as it is. How to avoid the execution of the commands and saving the text exactly as I entered it?

   $tee -a test.sh << EOF 
   if [[ $(/usr/bin/id -u) -ne 0 ]]; then
       echo You are not running as the root user.
       exit 1;
   fi;
   EOF
   if [[ 502 -ne 0 ]]; then
       echo You are not running as the root user. 
       exit 1;
   fi;

Complete script contains many more lines, but I chose /usr/bin/id -u as a sample.

CodePudding user response:

This has nothing to do with tee or appending to the file, it's how here-documents work. Normally variable expansion and command substitution is done in them.

Put single quotes around the EOF marker. This will treat the here-document like a single-quoted string, so that $ will not expand variables or execute command substitutions.

tee -a test.sh << 'EOF'
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
   echo You are not running as the root user.
   exit 1;
fi;
EOF
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
   echo You are not running as the root user. 
   exit 1;
fi;
  • Related