user2771150 user2771150 - 1 year ago 90
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


When I run the following code the echo is empty:

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.


export finalString
sudo -E bash -c 'echo -e "$finalString"'

Alternatively, you can have the current shell substitute instead:

sudo bash -c 'echo -e "'"$finalString"'"'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download