Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline bash script variables

Tags:

bash

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"
like image 943
Daniel Avatar asked Apr 01 '12 00:04

Daniel


People also ask

How do you set variables in Bash?

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.

What does $_ mean in Bash?

$_ (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.

What is $@ in bash script?

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.

What does $() mean in Bash?

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).


2 Answers

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.

like image 171
matt Avatar answered Oct 05 '22 01:10

matt


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"
like image 41
larsks Avatar answered Oct 05 '22 02:10

larsks