Bash-如何强制子shell字符串中的文本?

Bash-如何强制子shell字符串中的文本?,bash,variables,sudo,variable-expansion,Bash,Variables,Sudo,Variable Expansion,我想在使用sudobash-c执行shell命令时控制变量扩展 我知道我可以用普通的外壳来做: bash$ export FOO=foo bash$ export BAR=bar bash$ echo "expand $FOO but not "'$BAR'"" expand foo but not $BAR 如何使用sudobash-c执行上述操作 bash$ sudo bash -c "echo "expand $FOO but not "'$BAR'""" expand bash$ su

我想在使用
sudobash-c
执行shell命令时控制变量扩展

我知道我可以用普通的外壳来做:

bash$ export FOO=foo
bash$ export BAR=bar
bash$ echo "expand $FOO but not "'$BAR'""
expand foo but not $BAR
如何使用
sudobash-c
执行上述操作

bash$ sudo bash -c "echo "expand $FOO but not "'$BAR'"""
expand
bash$ sudo bash -c 'echo "expand $FOO but not "'$BAR'""'
expand  but not bar

您可以将其用于不希望展开的转义
$

$> bash -c "echo \"expand $FOO but not \"'\$BAR'"
expand foo but not $BAR
但是,我建议使用here doc以避免转义:

# original echo replaced with printf
$> printf 'expand %s but not %s\n' "$FOO" '$BAR'
expand foo but not $BAR

# prints in here-doc with bash
$> bash<<-'EOF'
printf 'expand %s but not %s\n' "$FOO" '$BAR'
EOF
expand foo but not $BAR
#原始回音替换为printf
$>printf'展开%s而不是%s\n'$FOO'$BAR'
展开foo而不是$BAR
#在这里用bash打印文档

$>bash传递参数,而不是试图生成一个字符串来传递给
bash

$ bash -c 'echo "expand $1 but not $2"' _ "$FOO" '$BAR'
expand 5 but not $BAR

(在由
-c
指定的脚本中,
\uuu
只是一个虚拟值,用于设置
$0

对于here doc,请使用sudo-E在根环境中工作。