接文档P328页
12.set 设置位置变量,shift移动位置变量。
set tom jack david -----$1 tom $2 jack $3 david
echo $*
tom jack david
shift 2 -----移动两个位置,$1,$2删除
echo $*
david
eg:
#!/bin/bash
#Name:shift
#Author : Hijack
#Usage:shift test
#Date:080320
while (($#>0))
do
echo "$*"
shift
done
[test@szbirdora 1]$ ./shift 1 2 3 4 5 6 7
1 2 3 4 5 6 7
2 3 4 5 6 7
3 4 5 6 7
4 5 6 7
5 6 7
6 7
7
13。 break n ---n 表明退出第几层循环,默认退出一层。continue n 相似
#!/bin/bash
#Name : Mulloop
#Author : Hijack
#Usage : break test
declare -i x=0
declare -i y=0
while true
do
while (( x<20 ))
do
x=$x+1
echo $x
if (( $x==10 ));then
echo "if"
break
fi
done
echo "loop end"
y=$y+1
if (($y>5));then
break
fi
done
[test@szbirdora 1]$ sh mulloop
1
2
3
4
5
6
7
8
9
10
if
loop end
11
12
13
14
15
16
17
18
19
20
loop end
loop end
loop end
loop end
loop end
#!/bin/bash
#Name : Mulloop
#Author : Hijack
#Usage : break test
declare -i x=0
declare -i y=0
while true
do
while (( x<20 ))
do
x=$x+1
echo $x
if (( $x==10 ));then
echo "if"
break 2
fi
done
echo "loop end"
y=$y+1
if (($y>5));then
break
fi
done
[test@szbirdora 1]$ sh mulloop
1
2
3
4
5
6
7
8
9
10
if
14.循环的IO重定向
使用">","|"等重定向符实现循环的IO重定向
如 while ;do
done >temp$$
for in
do
done |sort
eg
给文件的每行加一个行号,写入文件中
#!/bin/bash
#Name : loopred
#Author : Hijack
#Usage : add linenum to the file
#Program : read line to loop from file,add linenum,output to tempfile,mv tempfile to file
declare -i count=0
declare -i total=0
total=`sed -n "$=" $1`
cat $1 | while read line
do
(($count==0))&& echo -e "Processing file $1.....\n"> /dev/tty
count=$count+1
echo -e "$count\t$line"
(($count==$total))&& echo "Process finish,total line number is $count" > /dev/tty
done >temp$$
mv temp$$ $1
[test@szbirdora 1]$ sh loopred testmv
Processing file testmv.....linux
Process finish,total line number is 19
[test@szbirdora 1]$ vi testmvbash
1 /u01/test
2 /u01/test/1
3 /u01/test/1/11
4 /u01/test/1/forlist.sh
5 /u01/test/1/optgets.sh
6 /u01/test/1/whiletest.sh
7 /u01/test/1/func.sh
8 /u01/test/1/helloworld.sh
9 /u01/test/1/df.out
10 /u01/test/1/nullfile.txt
11 /u01/test/1/iftest.sh
12 /u01/test/1/myfile
13 /u01/test/1/opt2.sh
14 /u01/test/1/0
15 /u01/test/1/case.sh
16 /u01/test/1/nohup.out
17 /u01/test/1/hellfun.sh
18 /u01/test/1/parm.sh
19 /u01/test/1/test
15。在done后面加&使循环在后台运行,程序继续执行。
16.在函数内可使用local定义本地变量,local variable。
17.陷阱信号 trap --当一个信号发出传递给进程时,进程进行相关操做,信号包括中断等
trap ‘command;command’ signal-num #trap设置时执行命令
trap “command;command” signal-num #信号到达时执行命令
eg:
[root@linux2 ~]# trap "echo -e 'hello world\n';ls -lh" 2
[root@linux2 ~]# hello world ---ctrl+cide
total 100K
-rw-r--r-- 1 root root 1.4K Nov 14 16:53 anaconda-ks.cfg
drwxr-xr-x 2 root root 4.0K Nov 23 13:11 Desktop
-rw-r--r-- 1 root root 53K Nov 14 16:53 install.log
-rw-r--r-- 1 root root 4.9K Nov 14 16:53 install.log.syslog
drwxr-xr-x 2 root root 4.0K Nov 22 13:03 vmware函数