使用 heredoc 在 bash 脚本 sudo 中设置变量



我正在尝试运行一个切换用户的脚本(遵循此答案(。我无法在其中设置变量。我尝试了很多东西,但最基本的是:

sudo -u other_user bash << EOF
V=test
echo "${V}"
EOF

更现实的是,我正在做类似于以下内容的事情:

sudo -u other_user bash << EOF
cd
V=$(ls)
echo "${V}"
EOF

每次我尝试使用变量时V它都是未设置的。如何设置变量?

要抑制 heredoc 中的所有扩展,请引用符号 - 即<<'EOF',而不是<<EOF

sudo -u other_user bash -s <<'EOF'
cd
v=$(ls)      # aside: don't ever actually use ls programmatically
             #        see http://mywiki.wooledge.org/ParsingLs
echo "$v"    # aside: user-defined variables should have lowercase names; see
             #        http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
             #        fourth paragraph ("the name space of environment variable names
             #        containing lowercase letters is reserved for applications.")
EOF

如果要传递变量,请在-s之后传递它们,并从heredoc脚本中的位置引用它们(如$1$2等(。

最新更新