I'm on Mac and have just created an environment variable inside the .bash_profile directory, it works fine when I run:
$variable_name
I just want the know why the dollar sign is there and if it is possible to remove it. Any help would be appreciated 🙂
Best Answer
The $ (dollar sign) is there to reference variables in bash. You cannot remove it. Technically, it's called variable/parameter expansion. Basically the value of the variable is "expanded out".
Using variables in bash is pretty straight forward:
Example:
In the above script, we set
var1
to "Hello" andvar2
to user input (assume "World"). The next command prints out the contents of both variables on a single line:For more details, it's best to start with a good tutorial: BASH Programming - Introduction HOW-TO. Also have a look at the Bash Reference Manual
Tip:
You can enclose the variable in braces -
${variable}
. This serves to "protect" the variable from characters immediately following the variable name which would (incorrectly) become part of the variableExample:
The first echo would produce nothing since the variable
var1bar
doesn't exist where as the second echo would produce the wordfoobar
as expected. Personally, I use braces for all my variables as a matter of style.