Programmer
Programmer

Reputation: 73

Shell script with sudo sh

I want to make a script to install a program (ROS) and I need to write this line:

 sudo sh -c 'echo "TEXT VARIABLE TEXT" > systemFile'  # to write in systemaFile I need sudo sh

if echo is just fixed text, it works. If echo is text + variable it doesn't work.

I've tried with:

read f1 < <(lsb_release -a | grep Code* | cut  -f2)   #codename is writted in variable $f1
echo $f1 # retruns "quantal" as I expected
sudo sh -c 'echo "TEXT $f1 TEXT" > systemFile'  #f1 is empty, WHY?

Then I have to assign the variable inside the same instruction sudo sh, for example:

sudo sh -c ' read f1 < <(lsb_release -a | grep Code* | cut -f2) ; echo "TEXT $f1 TEXT" > systemFile'

sh: 1: Syntax error: redirection unexpected

Upvotes: 2

Views: 1704

Answers (4)

etheranger
etheranger

Reputation: 1273

Shell variables are only expanded in "double quotes", not in 'single quotes'.

$ v=value

$ echo $v
value

$ echo "$v"
value

$ echo '$v'
$v

You're starting a new instance of sh which then runs the command echo "TEXT $f1 TEXT" > systemFile.

Since $f1 has not been assigned within the new process, it's empty.


To fix this, you can expand $f1 and pass it in the command line:
sudo sh -c 'echo "TEXT '$f1' TEXT" > systemFile'

Or export it so it's available to the child process (using -E to preserve the environment, thanks anishsane):
export f1
sudo -E sh -c 'echo "TEXT $f1 TEXT" > systemFile'

Upvotes: 0

Farvardin
Farvardin

Reputation: 5414

use -E option to run sudo:

sudo -E sh -c 'echo "TEXT VARIABLE TEXT" > systemFile'

from man sudo:

-E

The -E (preserve environment) option indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the -E option is specified and the user does not have permission to preserve the environment.

Upvotes: 1

anishsane
anishsane

Reputation: 20970

This can work too:

sudo sh -c "echo 'TEXT $VARIABLE TEXT' > systemFile"

However, it is generally not recommended to un-necessarily run a command as sudo. You seem to want only redirection to be "sudoed". So try these options:

echo "TEXT $VARIABLE TEXT" | sudo tee systemFile >/dev/null
echo "TEXT $VARIABLE TEXT" | sudo dd of=systemFile

echo can be simple echo, or any other command you want. Note that this command is not being run under sudo.

Upvotes: 2

Kalpesh Gamit
Kalpesh Gamit

Reputation: 1104

Please try just like this script line

sudo sh -c 'echo TEXT '$f1' TEXT > systemFile'
sudo bash -c 'echo TEXT '$f1' TEXT > systemFile'

i have use this able script line in .sh file and its working fine.

Upvotes: 2

Related Questions