使用 heredoc 在 bash 脚本 sudo 中设置变量
Set variable in bash script sudo with heredoc
我正在尝试 运行 一个切换用户的脚本(在 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
时,它都未设置。如何设置变量?
要抑制 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 脚本中按位置引用它们(如 </code>、<code>
等)。
我正在尝试 运行 一个切换用户的脚本(在 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
时,它都未设置。如何设置变量?
要抑制 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 脚本中按位置引用它们(如 </code>、<code>
等)。