3

If I append this:

hi=11
export hi

to the .bashrc and then I su to this user with:

su - bela

then I:

echo $hi
11

Then it's working, the "hi" variable has the value of "11". But. When I:

su -c "echo $hi" bela

the variable "hi" has no value. Why?

(running on CentOS 6)

1 Answer 1

9

su -c "echo $hi" bela expands to the words su, -c, echo ​ and bela. Since the variable hi is not defined in your current shell, its expansion is empty. The command that is executed as user bela is echo ​.

Fix: su -c 'echo $hi' bela, with the single quotes protecting the $ from expansion… Not. The .bashrc file is only read by interactive shells. When you run su -c 'echo $hi' bela, this executes echo $hi as user bela. But since nothing is defining the variable hi, the command echo $hi expands to echo which still prints nothing.

2
  • yeah, interesting. i would have expected a non-login shell opened by su to read .bashrc, but it doesn't. moving the definition of $hi to .bash_profile works when used with su -c 'echo $hi' -l bela, though, when the login shell reads .bash_profile. Commented Nov 17, 2011 at 3:21
  • it works with ' ' :D Commented Nov 18, 2011 at 6:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .