0

I have a directory named "test 1" and I create a variable

dest="test\ 1"

I want to navigate to the directory using the cd command, so I type

cd $dest

which gives the output as

-bash: cd: too many arguments

while typing

cd test\ 1

actually works and changes the current directory to "test 1".

Now, I've read a few other questions and know that I've to type in

cd "$dest"

for it to work but I don't understand the reason why. Because $dest will basically substitute the value of the variable dest which is nothing but test\ 1. So why does this not work?

klaus_03
  • 3
  • 2
  • “Because $dest will basically substitute the value of the variable dest” No, it does more than that. – Gilles 'SO- stop being evil' Jan 05 '22 at 12:45
  • @Gilles'SO-stopbeingevil' but since I'm using a backslash, why doesn't it escape the space? Why does it treat test\ and 1 as 2 separate arguments? – klaus_03 Jan 05 '22 at 13:00
  • You can see the magic when using `set -x`: What `bash` actually performs is `cd 'test\' 1`. – pLumo Jan 05 '22 at 13:07
  • Because the backslash is not a special character unless there's also one of `*?[`. `dest='test\ [1]'; cd $test` would work. But of course `cd "$dest"` would not work. And `name='monthly report.txt'; file=$dest/$name; open "$file"` would not work, and wouldn't work with `open $file` either since `$file` would contain a mix of a file name and a wildcard pattern. – Gilles 'SO- stop being evil' Jan 05 '22 at 13:08
  • Does backslash actually escape the 'space' character? I mean if I run `echo "Hello \\"` the output is `Hello \\`. This means that the second backslash I added was used as an escape character. But if I run `echo "Hello\ K"`, the output is `Hello\ K`. Why isn't the backslash omitted in the output this time? – klaus_03 Jan 05 '22 at 13:26
  • Ignore the '`' above, the code formatting is messed up for some reason. – klaus_03 Jan 05 '22 at 13:33

0 Answers0