How to cd into a directory with blanks?
I have a directory called "foo bar baz blob". How can I
$ cd "foo bar baz blob"
I have tried with quoting (" and ') and with escaping the blanks (\ ). It does not work. Tab-completion does not work either.
I also have to issue commands with filename arguments that contain spaces. How do I do that? Even MidnightCommander (mc) fails in doing this.
EDIT
Over one year later, I finally found the source of my problem. I have overloaded the builtin cd with a function that automatically lists the files of the changed directory:
$ type cd
cd ist eine Funktion.
cd ()
{
if builtin cd $1; then
ls;
fi
}
$ cd Interner\ Speicher/
bash: cd: Interner: Datei oder Verzeichnis nicht gefunden
$ builtin cd Interner\ Speicher/
$ pwd
/run/user/1000/gvfs/mtp:host=%5Busb%3A002%2C018%5D/Interner Speicher
$ ls
Alarms DCIM Movies Notifications Podcasts SmsContactsBackup
Android Download Music Pictures Ringtones
The solution is easy: I just have to put double quotes around the $1:
if builtin cd "$1"; then
Ooof. Thank you.
You have three options:
- Escape the spaces using a backslash character
- Wrap the directory name in double-quotes (
""
) - Use TAB completion
Creating the directory:
user@pc:~/testfolder$ ls -l
total 0
user@pc:~/testfolder$ mkdir "foo bar baz blob"
user@pc:~/testfolder$ ls
foo bar baz blob
Method 1:
user@pc:~/testfolder$ cd foo\ bar\ baz\ blob/
user@pc:~/testfolder/foo bar baz blob$ echo "This works"
This works
Method 2:
user@pc:~/testfolder$ cd "foo bar baz blob"/
user@pc:~/testfolder/foo bar baz blob$ echo "This works, too"
This works, too
Method 3:
user@pc:~/testfolder$ cd foo<TAB><ENTER>
Based on your comment on the other answer: for accessing the file named, the escaping needs to be done as follows:
Eric\ Burdon\ -\ Starportrait\ -\ CD\ 1\ \(flac\).cue foo\ bar\ baz\ blob/
However, using TAB completion makes this process easier and avoids you having to escape the spaces manually.
I just created the same folder, in /home/abed, used tab completion, and it worked. See image below. If the folder was created at a different location, you'll have to navigate to that location before you can CD into your folder.
That's also OK. See image