如何在另一个 bash 脚本编写的 bash 脚本中转义 shell 命令
how to escape a shell command in bash script written by another bash script
谁能告诉我如何在另一个 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
谁能告诉我如何在另一个 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