Admittedly, I'm a bash neophyte. I always want to reach for Python for my shell scripting purposes. However, I'm trying to push myself to learn some bash. I'm curious why the following code doesn't work.
sh -c "F=\"123\"; echo $F"
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
Not an answer to the core question, but if anyone is looking to do this inline in a (subjectively) more elegant way than bash -c
:
( export MY_FLAG="Hello"; echo "$MY_FLAG" )
The syntax is nicer, no escape chars etc.
It doesn't work because variable expansion in the double-quoted string happens before the command is called. That is, if I type:
echo "$HOME"
The shell transforms this into:
echo "/home/lars"
Before actually calling the echo command. Similarly, if you type:
sh -c "F=\"123\"; echo $F"
This gets transformed into:
sh -c "F=\"123\"; echo"
Before calling a the sh
command. You can use single quotes to inhibit variable expansion, for example:
sh -c 'F="123"; echo $F'
You can also escape the $
with a backslash:
sh -c "F=\"123\"; echo \$F"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With