Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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)

share|improve this question

1 Answer 1

up vote 9 down vote accepted

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.

share|improve this answer
    
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. –  Tim Kennedy Nov 17 '11 at 3:21
    
it works with ' ' :D –  LanceBaynes Nov 18 '11 at 6:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.