Is it possible to remove the $ from an environment variable?
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 :)
Solution 1:
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:
- Don't use a "$" when setting a variable
- Use the "$" when referencing/calling a variable
Example:
#!/bin/bash
var1=Hello
read var2
echo $var1 $var2
exit
In the above script, we set var1
to "Hello" and var2
to user input (assume "World"). The next command prints out the contents of both variables on a single line:
Hello World
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 variable
Example:
var1=foo
echo $var1bar
echo ${var1}bar
The first echo would produce nothing since the variable var1bar
doesn't exist where as the second echo would produce the word foobar
as expected. Personally, I use braces for all my variables as a matter of style.