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.

I run the following script:

VAR="Test"
sh -c 'echo "Hello $VAR"'

But I get :

# ./test.sh
Hello

How can I "send" the variable VAR of my script to the shell created with sh -c?

share|improve this question

3 Answers 3

up vote 26 down vote accepted

Either use export to turn it into an environment variable, or pass it directly to the command.

VAR="Test" sh -c 'echo "Hello $VAR"'

VAR="Test"
export VAR
sh -c 'echo "Hello $VAR"'

Or simply use double quotes to allow interpolation without having to export anything nor pass the var to the command neither:

VAR='Test';
sh -c " echo 'Hello $VAR' "
share|improve this answer
    
Not really practical (I have several variables, and I don't want them to be environment variables), but it works, thanks! –  Matthieu Napoli Oct 24 '11 at 8:41
2  
@Matthieu: They are only set as environment variables for the children of your process, if that's what worries you. –  Piskvor Oct 24 '11 at 12:47
3  
Just FYI, You can also do export var="Test" in one line. –  user606723 Oct 24 '11 at 14:16
    
@Piskvor well thank you for the precision, that's perfect then. –  Matthieu Napoli Oct 25 '11 at 7:50

Here's yet another way to pass variables to sh -c (as positional arguments):

{
VAR="world"
VAR2='!'
sh -c 'echo "Hello ${0}${1}"' "$VAR" "$VAR2"
}
share|improve this answer
    
(+1) To keep it more in line with the normal $1 $2 expectation for script variables, it can have a dummy value for $0. This will allow $@ to work as expected, eg. sh -c 'echo "Hello $@"' _ "$VAR" "$VAR2" ` –  Peter.O Oct 24 '11 at 16:09
    
@Peter.O Rather than using "_", I would use "sh" or a sensible name to give to that command, since that $0 is displayed in the error/warning messages by the shell. –  Stéphane Chazelas Jan 26 '13 at 21:45

If you don't want to export them as environment variables, here's a trick you could do. Save your variabe definition to a file .var_init.sh and source it in your sub-shell like this:

.var_init.sh

VAR="Test"

from the command line:

sh -c ". .var_init.sh && echo \$VAR" # Make sure to properly escape the '$'

This way, you only set your variables at the execution of your subshell.

share|improve this answer

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.