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

Rya*_*ing 0 bash sudo su

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

sudo -u other_user bash << EOF
V=test
echo "${V}"
EOF
Run Code Online (Sandbox Code Playgroud)

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

sudo -u other_user bash << EOF
cd
V=$(ls)
echo "${V}"
EOF
Run Code Online (Sandbox Code Playgroud)

每次我尝试使用该变量时,V它都会被取消设置。如何设置变量?

Cha*_*ffy 5

要抑制定界规范中的所有扩展,请引用印记 - 即 ,而<<'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
Run Code Online (Sandbox Code Playgroud)

如果您想传递变量,请在 后传递它们-s,并在 Heredoc 脚本中按位置引用它们(如$1$2等)。


归档时间:

查看次数:

1622 次

最近记录:

7 年,7 月 前