user2771150 user2771150 - 1 year ago 53
Bash Question

Echo variable using sudo bash -c 'echo $myVariable' - bash script

I want to echo a string into the /etc/hosts file. The string is stored in a variable called

$myString
.

When I run the following code the echo is empty:

finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'


What am I doing wrong?

Answer Source
  1. You're not exporting the variable into the environment so that it can be picked up by subprocesses.

  2. You haven't told sudo to preserve the environment.

\

finalString="Hello\nWorld"
export finalString
sudo -E bash -c 'echo -e "$finalString"'

Alternatively, you can have the current shell substitute instead:

finalString="Hello\nWorld"
sudo bash -c 'echo -e "'"$finalString"'"'