2

How do I use "cd" to access a directory with a space, for example "XML 5.1 Final Fields" in a bash script

I tried cd XML 5.1 Final Fields

But it's giving the No such file or directory error.

This is the script:

#! /bin/bash
xmlfolder="XML/ \/5.1/ \/Final/ \/Fields"
xmlpath="/home/george/Desktop/m5u/test/$xmlfolder"
cd $xmlpath
ls /home/george/Desktop/m5u/test/    
XML 5.1 Final Fields
~/Desktop/m5u/test$ ll
drwxr-xr-x  9 george george      4096 Feb 18 12:44 XML 5.1 Final Fields

this is the error I get when I run the script

line 5: cd: /home/george/Desktop/m5u/test/XML\: No such file or directory
Tim
  • 33,500

1 Answers1

5

Your variable xmlfolder is wrong. It should be

xmlfolder=XML\ 5.1\ Final\ Fields

or ="XML 5.1 Final Fields"

You don't need the / in the path - as it's just one folder. You also don't need the "" if you are also using \. Pick one.


since your edit with the ls command, I can see there may be a space at the end of your folder name. I'd suggest you remove the space, either by renaming in nautilus or with the mv command.

If you want to keep the space, your variable name should be this:

xmlfolder=XML\ 5.1\ Final\ Fields\ 

or

xmlfolder="XML 5.1 Final Fields "

Note that if you use the First option with the \ character, you also need to refer to the variable with "", i.e. "$xmlfolder".


The error suggests that cd is unhappy with the path.

Try changing the cd command from this

cd $xmlpath

to

cd "$xmlpath"

To be perfectly honest, you shouldn't need to cd in a bash script. Just refer to everything with an absolute path.


In summary, your xmlfolder= line should be xmlfolder=XML\ 5.1\ Final\ Fields, and your cd line should be cd "xmlpath".

My pronouns are He / Him

Tim
  • 33,500