0

I could not cd to a directory, whose path name contains escaped spaces, that is represented by a variable.

The following command does not work.

~$ VAR="/mnt/e/documents/my\ files"
~$ cd $VAR
-bash: cd: too many arguments

However, when I use the path name as it is instead of assigning it to a variable, it works.

~$ cd /mnt/e/documents/my\ files
cd /mnt/e/documents/my files$ 

How to use cd with a variable as its argument, where the variable is a string with spaces that are escaped.

  • 1
    Always run your scripts through [shellcheck](https://www.shellcheck.net/) and follow its advice. – Shawn Jul 02 '20 at 14:19

1 Answers1

4

You have two problems:

Remove the backslash in the middle of my\ files. You only need to escape that space when you're not quoting it.

Add quotes around $VAR: cd "$VAR", otherwise it looks as though you are providing two parameters: "/mnt/e/documents/my" and "files"

Lorccan
  • 793
  • 5
  • 20