About Spaces in the Command Line

About Spaces in the Command Line

As we have seen, the shell uses spaces to separate the parts of the command line. Having two or more spaces separate a command from its options or its arguments doesn't change anything. When your shell acts on your command line, it breaks it into pieces by looking at where the spaces are. The following command lines both do the same thing:

 ls -l ls     -l 

But this one is very different:

ls - l

In the first two cases the shell sees two items: ls and -l . In the third case the shell sees three items: ls , - , and l .

But there are times when you have to include a space inside an argumentsuch as in a filename that itself contains spaces. Consider what would happen if you tried the command line

ls l /Desktop DB

If you don't do something special to handle spaces in command-line arguments, you will have problems. The shell treats the spaces as separators, and you will get unexpected and probably undesired results ( Figure 2.31 ).

Figure 2.31. When you use unprotected spaces in a command-line argument, the shell treats each word as a separate argument.
 user-vc8f9gd:~ vanilla$  ls l /Desktop DB  ls: /Desktop: No such file or directory ls: DB: No such file or directory user-vc8f9gd:~ vanilla$ 

Here are two ways to handle spaces safely in command-line arguments.

To protect spaces using quotes:

ls -l "/Desktop DB"

When you enclose the argument in quotes, the shell treats everything within the quotes as a single entity.

You may also use single quotes:

ls -l '/Desktop DB'


  • Using single quotes around a string of characters eliminates the effect of any special character, including the $ we saw earlier for environment variables . Compare

    echo 'hello $USER'


    echo "hello $USER"

    The first one echoes the exact characters, while the second identifies the user.

To protect spaces using the backslash:

  • ls /Desktop\ DB

    The backslash character ( \ ) is often used in Unix to escape a character. This means "make the next character not special." In this case it removes the special meaning of "separator" from the space character. This is called escaping a character .


  • Many Unix shells (including the default shell on Mac OS X) provide a feature called filename completion . When typing a part of a command line that is an existing filename, you can type just part of it and then press ; the shell tries to fill in the rest of the filename for you. The filename completion feature will also automatically escape spaces (and other special characters) in filenames.

Unix for Mac OS X 10. 4 Tiger. Visual QuickPro Guide
Unix for Mac OS X 10.4 Tiger: Visual QuickPro Guide (2nd Edition)
ISBN: 0321246683
EAN: 2147483647
Year: 2004
Pages: 161
Authors: Matisse Enzer

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net