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 '...'?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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"'
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 ';reboot #
Method 2
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"
}
Method 3
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.
Method 4
If you’re using sudo sh -c, the environment variables are not passed along, but you can get around it by using the --preserve-env argument:
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"'
Method 5
Thanks to “enharmonic” post, I’ve solved my problem.
I had to change this command that adds the “/etc/docker/daemon.json” file if not already present:
sudo echo "{ ${dqt}insecure-registries${dqt} : [${dqt}$ipaddress:5000${dqt}] }" >> $dockdaemoncfg
this command must be changed because it is not able to keep the content of both the variables “$ipaddress” and “${dqp}” (where is the double quotes dqt=’”’) and wrote nothing in their place into the file.
So thanks to “enharmonic” solution I successfully changed that as follows:
sudo VAR1="$IPaddress" VAR2="$dockdaemoncfg" bash -c 'echo "{ "insecure-registries" : ["$VAR1:5000"] }" >> "$VAR2"'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0