2

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?

1
  • It isn't cd that behaving strangely,in fact nothing is. You haven't quoted the subshell so the shell you are in expands what is returned from it. So whatever you do in the subshell is irrelevant. Commented Apr 23, 2015 at 10:32

1 Answer 1

8

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"
Sign up to request clarification or add additional context in comments.

3 Comments

or if you for some reason want to use a subshell, quote the subshell "$(echo $input_path)"
It seems rather obvious now that you pointed it out! Thank you very much, that has solved my problem. I was also able to fix errors that occurred later on when filenames have spaces by doing the same thing - wrapping the variable in quotes.
@TomBennett nice to see that it was helpful to you :) Yes, this is one of those things that can get confusing until "pop", they become obvious!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.