Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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?

like image 827
user2771150 Avatar asked Oct 17 '25 14:10

user2771150


2 Answers

  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"'"'
like image 113
Ignacio Vazquez-Abrams Avatar answered Oct 20 '25 04:10

Ignacio Vazquez-Abrams


You can do this:

bash -c "echo -e '$finalString'"

i.e using double quote to pass argument to the subshell, thus the variable ($finalString) is expanded (by the current shell) as expected.

Though I would recommend not using the -e flag with echo. Instead you can just do:

finalString="Hello
World"
like image 38
Jahid Avatar answered Oct 20 '25 04:10

Jahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!