4

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
  • 21,542
  • 10
  • 90
  • 108
user2771150
  • 722
  • 4
  • 10
  • 33

2 Answers2

6
  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
  • 776,304
  • 153
  • 1,341
  • 1,358
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
  • 21,542
  • 10
  • 90
  • 108