Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add path with space in Bash variable

Tags:

How can I add a path with a space in a Bash variable in .bashrc? I want to store some variables in .bashrc for paths and I encountered a path with a space in it.

I tried to add it between ' ' or use the escape character \, but it didn't help:

games=/run/media/mohamedRadwan/games\ moves    # this doesn't work games='/run/media/mohamedRadwan/games  moves'  # or this games="/run/media/mohamedRadwan/games  moves"  # or this 

... when I run:

mount $games 

... it throws an error indicating that it's only trying to mount /run/media/mohamedRadwan/games.

But when I run echo $games, it shows the full value, /run/media/mohamedRadwan/games moves.

How can I solve this?

like image 234
Mohamed ِRadwan Avatar asked May 04 '17 15:05

Mohamed ِRadwan


People also ask

How do I set the PATH variable in bash?

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/. bash_profile, ~/. bashrc, or ~/.

How do you handle a space in a PATH in Linux?

There are two main ways to handle such files or directories; one uses escape characters, i.e., backslash (\<space>), and the second is using apostrophes or quotation marks. Using backslash can be confusing; it's easy and better to use quotation marks or apostrophes.


2 Answers

mount /dev/sda9 "$games" 

As mentioned, always quote variable dereferences. Otherwise, the shell confuses the spaces in the variable's value as spaces separating multiple values.

like image 71
bishop Avatar answered Sep 29 '22 10:09

bishop


When variable contains spaces, variable expansion and then word splitting will result to many arguments, echo command will display all arguments but other program or function may handle arguments another way.

Surrounding variable with double quotes will prevent arguments to be splitted

printf "'%s'\n" $games  printf "'%s'\n" "$games" 
like image 31
Nahuel Fouilleul Avatar answered Sep 29 '22 12:09

Nahuel Fouilleul