On 06/01/11 12:05, Patrick O'Callaghan wrote:
On Wed, 2011-06-01 at 09:59 -0700, JD wrote:
> Since a space is Unix's and Linux's chosen field separator,
> I think having a space in filenames should be avoided. there
> are many situations where spaces in filenames cause problems.
> A simple example:
>
> for i in *; do
> [ -f $i ]&& echo $i is a file
> done
>
> you will see that the file with spaces in it's name
> will not be recognized as a file because each
> space-separated member of that file name
> becomes a separate argument
> when * is expanded by the shell.
No, each filename counts as one argument, even if it has spaces in it.
The problem arises when you *use* the argument. The above should read:
for i in *; do
[ -f "$i"]&& echo "$i" is a file
done
(the quotes are optional in the echo case obviously).
poc
The quotes are not optional.
Take a look at this example:
$ ls -1
a b c d
j
k
l
m
$ for i in *; do
ls -l $i
done
/bin/ls: cannot access a: No such file or directory
/bin/ls: cannot access b: No such file or directory
/bin/ls: cannot access c: No such file or directory
/bin/ls: cannot access d: No such file or directory
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 j
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 k
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 l
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 m
$ for i in *; do
ls -l "$i"
done
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 a b c d
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 j
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 k
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 l
-rw-r--r-- 1 jd jd 0 Jun 1 12:10 m
I have run into more scripts that had omitted the quotes
in the "use" of the variable, and thus failed.