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 '...'?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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"'
Avoid using double quotes around the shell code to allow interpolation as that introduces command injection vulnerabilities like in:
sh -c " echo 'Hello $VAR' "
causing a reboot if called when
$VAR contains something like
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:
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.
If you're using
sudo sh -c, the environment variables are not passed along, but you can get around it by using the
export VAR="test for exporting" sudo --preserve-env=VAR sh -c 'echo "This is a $VAR"'
This passes along just the variables you need rather than using
sudo -E which passes along your entire set of environment variables. From Sudo Manual:
--preserve-env=list Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment. The security policy may return an error if the user does not have permission to preserve the environment.
Or, you could assign it directly as:
export VAR="test for exporting" sudo VAR1="VAR" sh -c 'echo "This is a $VAR1"'