接文檔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函數