【问题标题】:how to escape a shell command in bash script written by another bash script如何在另一个bash脚本编写的bash脚本中转义shell命令
【发布时间】:2024-01-06 07:19:01
【问题描述】:

谁能告诉我如何在另一个 bash 脚本编写的 bash 脚本中转义 shell 命令?

例如,我的脚本如下所示:

sudo sh -c "echo \"if who | grep tty | grep \`whoami\` > /dev/null\"        > test.sh"  
sudo sh -c "echo \"then\"                                                  >> test.sh"
sudo sh -c "echo \"    echo ' log in '\"                                       >> test.sh"
sudo sh -c "echo \"else\"                                                  >> test.sh"
sudo sh -c "echo \"    exit\"                                              >> test.sh"
sudo sh -c "echo \"fi\"                                                    >> test.sh"

我希望脚本 test.sh 包含

if who | grep tty | grep `whoami`> /dev/null
then
    echo 'user  is log in '
else
    exit
fi

其实whoami这个命令被root替换了。

解决方案:

sudo tee /usr/local/bin/test.sh  << 'EOF'
if who | grep tty | grep `whoami`> /dev/null
then
    echo 'user  is log in '
else
    exit
fi
EOF

【问题讨论】:

  • 我不明白为什么不在脚本中简单地编写命令?为什么你使用sh -c 的东西?由于不清楚,请在您的帖子中添加更多详细信息。
  • 不确定是否理解您的问题。我有一个生成其他脚本的主脚本。我的 test.sh 脚本需要由主脚本在特定计算机上动态生成。
  • 但是为什么要让 echo 以不同的用户身份运行呢?
  • 因为主脚本可以由普通用户执行,而生成的脚本需要放在 /usr/local/bin 时使用 sudo 。我的示例已被简化,但我的 test.sh 脚本需要位于 /usr/local/bin

标签: bash shell escaping heredoc


【解决方案1】:

使用heredoc 最容易处理复杂的引号:

cat > test.sh << 'EOF'
if who | grep tty | grep `whoami`> /dev/null
then
    echo 'user  is log in '
else
    exit
fi
EOF

【讨论】:

  • 感谢您的想法。由于我没有成功将 'sudo' 与 'cat' 一起使用,我使用 'tee' 来代替
最近更新 更多