繁体   English   中英

Bash-如何在子shell字符串中强制使用文字?

[英]Bash - How to force literal in subshell string?

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

我知道我可以通过普通的shell来做到这一点:

bash$ export FOO=foo
bash$ export BAR=bar
bash$ echo "expand $FOO but not "'$BAR'""
expand foo but not $BAR

如何使用sudo bash -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

传递参数,而不是尝试生成要传递给bash的字符串。

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

_只是一个虚拟值,可在-c指定的脚本中设置$0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM