首页 > 解决方案 > 如何在另一个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

标签: bashshellescapingheredoc

解决方案


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

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

推荐阅读