for命令基本格式:
用法如下:
如果确实想在列表中使用单引号,有两种方法:
(1) 使用 '\'转义单引号
显然没有路径为~/*的文件和文件夹,程序什么都不会输出
for var in list
do
commands
done
用法如下:
一、直接遍历一个列表
$ cat test.sh
#!/bin/bash
for n in 1 2 3 4 5 6
do
echo "n=$n"
done
$ ./test.sh
n=1
n=2
n=3
n=4
n=5
n=6
注意在列表中如果含有单引号,会把单引号包括起来的字符视为一个整体。
$ cat test.sh
#!/bin/bash
for val in I don't know if I'm a good man
do
echo "n=$val"
done
$ ./test.sh
n=I
n=dont know if Im
n=a
n=good
n=man
如上所示:单引号包括的内容被当做一个整体,里面的空格不会起分隔作用。
如果确实想在列表中使用单引号,有两种方法:
(1) 使用 '\'转义单引号
$ cat test.sh
#!/bin/bash
for val in I don\'t know if I\'m a good man
do
echo "n=$val"
done
$ ./test.sh
n=I
n=don't
n=know
n=if
n=I'm
n=a
n=good
n=man
(2) 使用双引号将含有单引号的字串包起来。
$ cat test.sh
#!/bin/bash
for val in I "don't" know if "I'm" a good man
do
echo "n=$val"
done
$ ./test.sh
n=I
n=don't
n=know
n=if
n=I'm
n=a
n=good
n=man
如果一个字串中含有空格,要用双引号包起来。
$ cat test.sh
#!/bin/bash
for val in I "don't know if I'm" a good man
do
echo "n=$val"
done
$ ./test.sh
n=I
n=don't know if I'm
n=a
n=good
n=man
二、从变量中读取列表
$ cat test.sh
#!/bin/bash
list="I don't know if I'm a good man"
for val in $list
do
echo "n=$val"
done
$ ./test.sh
n=I
n=don't
n=know
n=if
n=I'm
n=a
n=good
n=man
三、读取命令中的值
$ cat test.txt
apple pear banana orange
$ cat test.sh
#!/bin/bash
for val in `cat test.txt`
do
echo "n=$val"
done
$ ./test.sh
n=apple
n=pear
n=banana
n=orange
四、使用通配符读取目录
$ cat test.sh
#!/bin/bash
ifs_old=$IFS
IFS=$':'
for val in ~/*
do
if [ -d $val ]
then
echo "$val is a directory"
elif [ -f $val ]
then
echo "$val is a file"
fi
done
IFS=$ifs_old
$ ./test.sh
/home/jix/begin one day.sh is a file
/home/jix/code is a directory
/home/jix/Desktop is a directory
/home/jix/Documents is a directory
/home/jix/Downloads is a directory
/home/jix/grep.txt is a file
/home/jix/grep.txt1 is a file
/home/jix/Music is a directory
/home/jix/Pictures is a directory
/home/jix/Public is a directory
/home/jix/Templates is a directory
/home/jix/Videos is a directory
注意:for val in ~/* 中的~/*不能写为"~/*",写为"~/*"会被当做一个字符串处理,
显然没有路径为~/*的文件和文件夹,程序什么都不会输出
$ cat test.sh
#!/bin/bash
ifs_old=$IFS
IFS=$':'
for val in "~/*"
do
if [ -d $val ]
then
echo "$val is a directory"
elif [ -f $val ]
then
echo "$val is a file"
fi
done
IFS=$ifs_old
$ ./test.sh
$