1

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.

Alex
  • 11
  • 4
  • The dollar sign has a special meaning in this case. You can escape it with a backslash. https://stackoverflow.com/questions/2500436/how-does-cat-eof-work-in-bash – David Lukas Nov 24 '21 at 15:55

1 Answers1

1

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;
Barmar
  • 741,623
  • 53
  • 500
  • 612