【问题标题】:How to avoid the command execution when appending lines to a file将行附加到文件时如何避免命令执行
【发布时间】:2022-01-03 00:01:49
【问题描述】:

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

   $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 作为示例。

【问题讨论】:

标签: linux append tee


【解决方案1】:

这与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;

【讨论】: