Bash script built-in variables

Admittedly, I'm a neophyte bash. I always want to contact Python for my shell scripts. However, I am trying to force myself to learn some bash. I am curious why the following code does not work.

sh -c "F=\"123\"; echo $F" 
+8
bash
source share
1 answer

This does not work because the expansion of a variable in a double-quoted string occurs before the command is called. That is, if I type:

 echo "$HOME" 

The shell will convert this to:

 echo "/home/lars" 

Before calling the echo command. Similarly, if you type:

 sh -c "F=\"123\"; echo $F" 

This translates to:

 sh -c "F=\"123\"; echo" 

Before invoking the sh command. You can use single quotes to prevent variable expansion, for example:

 sh -c 'F="123"; echo $F' 

You can also avoid $ with a backslash:

 sh -c "F=\"123\"; echo \$F" 
+13
source share

All Articles