2

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
shj
  • 1,558
  • 17
  • 23

2 Answers2

3

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    For here-doc, use sudo -E to work in root env. http://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo – shj Aug 25 '16 at 14:46
0

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.)

chepner
  • 497,756
  • 71
  • 530
  • 681