Reputation: 35
I am writing a shell script to enter multiple folders.
I am currently storing the name of folder in a shell variable as so path="October\ @012/"
.
If I do cd $path
I receive the error bash: cd: October\: No such file or directory
What am I doing wrong?
Upvotes: 1
Views: 6739
Reputation: 12514
This is the (principal) function of double quotes, and it's true in csh and *sh shells.
cd "$TARGET"
should do it.
Shell variables are expanded within "..."
(unlike within '...'
), but the quoted text is regarded as a single argument when the shell parses the command line to construct the strings which are passed to the program.
For example:
% ls -F
October @012/
% TARGET="October @012"
% cd $TARGET
bash: cd: October: No such file or directory
% cd "$TARGET"
% pwd
/tmp/t/October @012
%
Simple!
What you're doing wrong in your initial example is escaping the space inside the quotes. The space doesn't have to be escaped twice, and because this redundant \
is appearing inside the quotes, it just inserts a backslash into the TARGET variable. For example:
% TARGET="October\ @012" # wrong!
% ls
October @012/
% cd $TARGET
bash: cd: October\: No such file or directory
% cd "$TARGET"
bash: cd: October\ @012: No such file or directory
%
This setting of TARGET
would only work if the directory were named October\ @012
, with a backslash in it (not recommended!):
% mkdir October\\\ @012
% ls -F
October\ @012/
% cd "$TARGET"
% pwd
/tmp/t/October\ @012
%
(EDITED to add example)
Upvotes: 7
Reputation: 1582
EDIT: I originally had written to recommend using curly braces. I wrote this when I had awoke in the middle of the night and have modified my answer.
First off it really depends on which shell you are writing your script in. If it is bash then you could try using quotation marks around your variable name:
TARGET="October @012"
cd "$TARGET"
This may work in other shells as well. I would suggest you try it.
EDIT:
On re-examining this it appears you are escaping the wrong part in your expression. Try this:
path="October \@012"
cd "$path"
Upvotes: 1