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?
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 ~/.
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.
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.
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"
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