有人可以告诉我如何在另一个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