In Bash, assigning values to variables is done using T=content
, with no spaces before or after the equal sign.
Despite that I've seen the following in a shell script PWD= /bin/pwd
containing a space on the right side of the equals sign.
What's the purpose of it have a space?
Naming rules Variables can only contain letters, numbers, and underscores. Variable names can start with a letter or an underscore, but can not start with a number. Spaces are not allowed in variable names, so we use underscores instead of spaces.
But the PATH environment variable doesn't use spaces to separate directories. It uses semicolons. This means that if you want to add a directory with spaces in its name to the path, you don't need quotation marks since spaces mean nothing to the PATH environment variable.
The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command. The following commands removed the spaces from the variable, $Var by using `sed` command and [[:space:]].
In the example PWD= /bin/pwd
, the variable PWD
is set to the empty string before executing the command /bin/pwd
. The change only takes effect for that line.
This can be useful to make a temporary change to a variable for the purposes of running a command, without affecting the original value. Another example of this would be when using read
, to set a different IFS
:
IFS=, read a b c <<<"comma,separated,list"
This sets the field separator to a comma so that a
, b
and c
are read correctly. After this line, IFS
returns to the default value, so the rest of the script isn't affected.
Perhaps on some systems, the output of the command pwd
is affected by the value of the variable PWD
, so doing this prevents problems caused by PWD
being overwritten elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With