Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of variables with space after the (=) sign?

Tags:

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?

like image 547
kaneda Avatar asked Nov 17 '14 11:11

kaneda


People also ask

Can strings contain spaces when assigned to variables?

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.

Can environment variable names have 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.

How do you remove spaces from a 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:]].


1 Answers

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.

like image 108
Tom Fenech Avatar answered Sep 23 '22 13:09

Tom Fenech