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