将行附加到文件时如何避免命令执行

How to avoid the command execution when appending lines to a file

我正在尝试使用命令行将脚本的内容保存到文件中,但我注意到当 tee 命令检测到 linux 命令时,例如 $(/usr/bin/id -u),它执行命令而不是按原样保存行。如何避免执行命令并完全按照我输入的方式保存文本?

   $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;

完整的脚本包含更多行,但我选择 /usr/bin/id -u 作为示例。

这与 tee 或附加到文件无关,这是 here-documents 的工作方式。通常在其中完成变量扩展和命令替换。

EOF 标记两边加上单引号。这会将 here-document 视为单引号字符串,因此 $ 不会扩展变量或执行命令替换。

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;