【问题标题】:Set variable in bash script sudo with heredoc [duplicate]使用heredoc在bash脚本sudo中设置变量[重复]
【发布时间】:2018-10-01 13:54:03
【问题描述】:

我正在尝试运行一个切换用户的脚本(在this answer 之后)。我无法在其中设置变量。我尝试了很多东西,但最基本的是:

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

更现实地说,我正在做类似以下的事情:

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

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

【问题讨论】:

  • 无法在我当前的环境中进行测试,但我很确定 "${V}" 在您的外壳中而不是在其他用户的外壳中展开。尝试转义$
  • @Aaron 就是这样!转换为答案,我会接受
  • Protip:就像您可以打印变量值以尝试调试脚本一样,您可以打印此处文档的内容以确保您传递了正确的数据。只需将sudo -u other_user bash 替换为cat,你就会看到你的shell 得到了什么以及它为什么会这样
  • @RyanHaining Charles Duffy 的回答可能更好,不妨接受这个:)

标签: bash sudo su


【解决方案1】:

要抑制heredoc 中的所有扩展,请引用印记——即&lt;&lt;'EOF',而不是&lt;&lt;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 等)。

【讨论】: