[英]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.