user1631862
user1631862

Reputation:

cd to an unknown directory name with spaces in a bash script

I've looked at some of the posts that have similar issues, but I can't extrapolate some of the solutions to fit my own needs, so here I am.

I have a simple shell script and I need it to cd into a directory with a space in the name. The directory is in the same place every time (/home/user/topleveldir) but the directory name itself is unique to the machine, and has a space in it (/home/user/topleveldir/{machine1}\ dir/, /home/user/topleveldir/{machine2}\ dir/). I'm confused as to the best method to cd into that unique directory in a script.

Upvotes: 1

Views: 982

Answers (2)

You need to quote that space character, so that the shell knows that it's part of the argument and not a separator between arguments.

If you have the directory directly on that command line in the script, use single quotes. Between single quotes, every character is interpreted literally except a single quote.

cd '/home/user/topleveldir/darkstar dir/'

If the directory name comes from a variable, use double quotes around the command substitution. Always use double quotes around command substitutions, e.g. "$foo". If you leave out the quotes, the value of the variable is split into separate words which are interpreted as glob patterns — this is very rarely desirable.

directory_name='darkstar dir'
…
cd "/home/user/topleveldir/$directory_name"

Upvotes: 1

Alex Gitelman
Alex Gitelman

Reputation: 24722

I don't see why something like following would not work

baseDir=/home/user/topleveldir
machine=<whatever machine name>
cd "$baseDir/$machine dir"

Upvotes: 2

Related Questions