Re: Stupid spaces

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Looking at this thread, quite a few people seem to have problems with
shell quoting.

As a general rule, literal values should be contained within single
quotes, i.e.:

	file_path='/some/where/Test Folder/'

while variable references should almost always be contained within
double quotes:

	cd "$file_path"

Within double quotes, variable expansions (e.g. $foo), command
substitutions (e.g. `foo` or $(foo)), arithmetic substitutions (e.g. 
$[1+2] or $((1+2)) ) and similar (i.e. anything beginning with ` or $)
are still evaluated, and the backslash character can be used to quote
any of $ ` " \ or a newline.

Within single quotes, everything up to the next single quote is taken
literally (including the backslash character). If you need to include
a single quote, use '\'', e.g.:

	$ echo 'it'\''s'
	it's

[This parses as 'it' \' 's' (without the spaces), which the shell
interprets is it ' s (again, without the spaces).]

Unquoted variable expansions will subsequently be split into words so,
as has already been noted, the commands:

	file_path='/some/where/Test Folder/'
	cd $file_path

will result in the "cd" built-in command being called with two
arguments, namely:

	/some/where/Test
and:
	Folder/

For this reason, variable references should usually be enclosed in
double quotes; failure to do so is the main reason why scripts fail on
filenames (or other arguments) which contain spaces.

If you have trouble with shell syntax issues generally, it may help to
compile and install the following program:

	#include <stdio.h>

	int main(int argc, char **argv)
	{
		int i;
		for (i = 0; i < argc; i++)
			printf("argv[%2d] = '%s'\n", i, argv[i]);
		return 0;
	}

You can then use it to see exactly what the shell is doing with your
command line before it gets to the program, e.g.:

	$ file_path='/some/where/Test Folder/'
	$ args $file_path
	argv[ 0] = '/usr/local/bin/args'
	argv[ 1] = '/some/where/Test'
	argv[ 2] = 'Folder/'
	$ args "$file_path"
	argv[ 0] = '/usr/local/bin/args'
	argv[ 1] = '/some/where/Test Folder/'

It may also help to read the bash(1) manpage. OK, so it's a bit more
than a "page" (I get 60 pages for 1.x, 86 pages for 2.x) but, if you
use the command line regularly, you could easily spend hundreds of
hours per year using bash.

-- 
Glynn Clements <glynn.clements@xxxxxxxxxx>
-
: send the line "unsubscribe linux-admin" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Newbie]     [Audio]     [Hams]     [Kernel Newbies]     [Util Linux NG]     [Security]     [Netfilter]     [Bugtraq]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux Device Drivers]     [Samba]     [Video 4 Linux]     [Git]     [Fedora Users]

  Powered by Linux