I'd like to control variable expansion when executing a shell command using sudo bash -c
.
I know I can do it from a normal shell:
bash$ export FOO=foo
bash$ export BAR=bar
bash$ echo "expand $FOO but not "'$BAR'""
expand foo but not $BAR
How can I do the above using 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
You can use this with escaped $
that you don't want to expand:
$> bash -c "echo \"expand $FOO but not \"'\$BAR'"
expand foo but not $BAR
However I recommend using here-doc to avoid escaping:
# 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
Pass arguments rather than trying to generate a string to pass to bash
.
$ bash -c 'echo "expand $1 but not $2"' _ "$FOO" '$BAR'
expand 5 but not $BAR
(The _
is just a dummy value to set $0
in the script specified by -c
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.