Ubuntu – How to pass a pathname with a space in it to cd inside of a script

bashscripts

I am working on Windows 10 and am using the Ubuntu subsystem. Often I need to change between Windows directories and Linux ones, so I wanted to write a script that automatically converts a Windows path into a Linux path and then changes directories. I wrote the conversion script just fine, but for some reason I can't pass the path to cd.

Example:

$ mkdir temp\ space
$ temp=$(echo "temp\ space") # simulate script that converts path
$ echo $temp
temp\ space
$ cd $temp
-bash: cd: temp\: No such file or directory

Edit:

In hind sight I realized the this actually wasn't my problem, I must have been tired when I wrote this and introduce this bug into my minimal example. My real problem was that I didn't know how to run a shell script in the current shell instead of a subshell. Thank you everyone for your help!

Best Answer

When you quote the string, "", you're saying "Use this string". There is no need to escape the space, because you've encapsulated your string with double-quotes.

When you're using the terminal, and you do not encapsulate the string in quotes, the terminal wants to see the space as a new argument, and gets confused. Are you familiar with CSV files? Think about a CSV file that has a comma found as part of one of the cell values. In both cases, we need to make sure to clarify the delimiter. While CSV files will use a comma, bash and programs often use spaces to delimit, or separate command line arguments and their values.

So, you either need to quote your strings that contain spaces, or escape the spaces in the string; not both.

Because of this, there are a lot of 'best practices' when using BASH variables. For example, you'll always want to surround them in quotes, to workaround the exact issue you're experiencing:

mv thisFile My Space Directory/ # What moves where?
mv thisFile "My Space Directory/" # It is clear what to move where
mv thisFile My\ Space\ Directory/ # Again, clear to the computer
mv thisFile "${tmp}" # Be sure string is not escaped.

Typically, you'll only escape the spaces when you're interacting with the terminal directly, yourself, for things such as Tab completion or doing other manual adjustments.

Also, take note that bash treats ' and " slightly differently, in that ' will not allow expansion, while " will. For example:

$ BANANA_COUNT=4
$ newVar1="We have this many bananas: ${BANANA_COUNT}"
$ newVar2='We have this many bananas: ${BANANA_COUNT}'
$ echo $newVar1
We have this many bananas: 4
$ echo $newVar2
We have this many bananas: ${BANANA_COUNT}
Related Question