Tom Bennett
Tom Bennett

Reputation: 179

Bash: use cd command on a variable including spaces

I am attempting to change directory within a script in order to perform a bunch of operations using relative paths. The folder is a variable named $input_path:

cd $(echo "$input_path")

If there is a space in the variable, for example "/home/user/test directory/subfolder", the script returns an error:

./test_currently_broken.sh: line 86: cd: "/home/user/test: No such file or directory

I have tried various ways to escape the spaces:

# escape spaces using backslashes, using sed
input_path=$(echo "$input_path" | sed 's/ /\\ /g')

or

# wrap input path with awk to add quotes
input_path=$(echo "$input_path" | awk '{print "\"" $0 "\""}')

or

# wrap in single quotes using sed
input_path=$(echo "$input_path" | sed -e "s/\(.*\)/'\1'/")#

But none fix the error - it still fails to change directory. I have confirmed that the directory it is attempting to change to definitely exists, and cding works outside of this script.

Is there a solution to this strange behaviour of cd?

Upvotes: 2

Views: 8361

Answers (1)

fedorqui
fedorqui

Reputation: 289515

Why don't you just...

cd "$input_path"

since it is quoted, there won't be any problem with spaces.

By saying cd $(echo "$input_path") you are in fact saying cd my path, whereas you want to do cd "my path". Thus, as commented by JID below, you can also say cd "$(echo $input_path)" because the important quotes are the ones that are "closer" to cd.


If you don't quote, cd sees:

cd my path

So it tries to cd my, whereas if you quote it sees:

cd "my path"

Upvotes: 8

Related Questions