1

I want to correctly export a variable. In order to do so I have to understand several variations in syntax. I've seen the following mechanisms of exporting a variable. In this case I am using .bashrc:

  1. export MY_VARIABLE=$USER/.gradle --$

  2. export MY_VARIABLE="$USER/.gradle" --Quotes

  3. export MY_VARIABLE=USER/.gradle --No $

  4. export $MY_VARIABLE=$USER/.gradle --All the $

What is the significance of the $ sign in these cases? Why is it sometimes used and other times not?

Do we need quotes in cases where there are no spaces in the path? What if the path is contained in $USER contains spaces?

Why no $ on the left hand side of export?

2

Tokens such as export, declare, and the like explicitly use variable names as parameters. $ can generally be understood to mean "the value of", so $variable means "the value of variable". Take this set of commands:

foo=bar
bar=baz
export $foo
( echo "$foo" )

What will happen here is that you will get one blank line of output. This is because in the export command, $foo is actually bar (the value of foo), so the actual command executed is export bar. Since foo is not exported, its default value is null. However, if the last line were:

( echo "$bar" )

You would get the output of baz, the value of bar which had been exported into forthcoming subshells.

It is generally a very good idea to use weak quotes (""") around all of your variable references, for reasons including but not limited to the one you mention (i. e. spaces in filenames and paths). For example, if we had:

if [ $letter == a ]; then echo "ayyyy"; fi

but letter were empty, the shell would attempt to execute

if [  == a ]

which is a syntax error, but with quotes:

if [ "$letter" == a ];

becomes

if [ "" == a ];

which is valid.

  • Would point out that you are doing two things with the export statement: first is "assignment" of a value to the variable and the second is "exporting" of that value to the process (and all child processes). See also tldp.org/LDP/abs/html/variables.html – Thomas N May 23 '17 at 16:14
  • True. Though I habitually give all my variables values first and export them separately. – DopeGhoti May 23 '17 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.