3

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?

Jahid
  • 19,822
  • 8
  • 86
  • 102
user2771150
  • 662
  • 4
  • 10
  • 30

2 Answers2

4
  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"'"'
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
1

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"
Jahid
  • 19,822
  • 8
  • 86
  • 102