32

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?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Mohamed ِRadwan
  • 767
  • 2
  • 8
  • 17

2 Answers2

26
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.

bishop
  • 37,830
  • 11
  • 104
  • 139
5

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"
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36