bash - 如何在另一个bash脚本编写的bash脚本中转义shell命令
问题描述
谁能告诉我如何在另一个 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
解决方案
使用heredoc最容易处理复杂的引号:
cat > test.sh << 'EOF'
if who | grep tty | grep `whoami`> /dev/null
then
echo 'user is log in '
else
exit
fi
EOF
推荐阅读
- linux - 在 GCP VM /var/log 中占用更多空间。如何减少它?
- javascript - 从缓动函数中找到三次贝塞尔曲线
- android - 传入一个字符串以用作 Room 查询的一部分
- ruby-on-rails - 如何在 Rails <= 4 中加密环境变量
- python - 使用 xPath 表达式的 CSV 文件中的错误输出
- reactjs - 如何使用反应钩子重新获取 API
- c# - 如何制作 linq lambda 表达式
- java - Java 8 分组并在列表中求和
- > 对象
- python - 如何在 Pyspark 上依次运行多个 Spark 作业?
- javascript - 我想单击一次按钮,每当我刷新页面时,计时器仍会继续计数