1

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.

2 Answers 2

2

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

baseDir=/home/user/topleveldir machine=<whatever machine name> cd "$baseDir/$machine dir" 
Sign up to request clarification or add additional context in comments.

4 Comments

it is quoted and needs no escape. Just tested it.
I probably should have mentioned that the machine name is dynamically generated, so I actually don't know what it is. My current command is grepping the ls of the contents of topleveldir to return the dir I want, but CDing into it is where I'm having trouble. Sorry for being unclear!
It makes no difference how you assign variable machine. It will still work as long as quoted properly.
Thanks Alex, I appreciate the feedback. Easy solution, dunno why I didn't think of it myself. Thanks again, and have a great weekend!
1

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" 

Comments