Linux程式設計(8)第二章:shell程式設計(7)shift trap unset exit find grep 指令的執行 here 文檔
- 1. shift
- 2. trap 指令
- 3. unset 指令
- 4. find 指令
- 5. grep 指令
- 6. 指令的執行
-
- 6.1 算術擴充
- 7. here 文檔
1. shift
把所有的參數變量左移一位,使 $2 變成 $1,以此類推。
#!/bin/sh
while [ "$1" != "" ]; do
echo "$1"
shift
done
exit 0
2. trap 指令
trap 指令用于指定在接收到信号後要采取的行動。
它的一種常見用途是在腳本程式被中斷時完成清理工
-
常見信号:
HUP(1) 挂起,通常因終端掉線或使用者退出而引發
INT(2) 中斷, 通常因按下 ctrl+c 組合鍵引發
QUIT(3) 退出, 通常因按下 ctrl+\ 組合鍵引發
ABRT(6) 報警, 通常用來處理逾時
ALRM(14)終止, 通常因某些嚴重錯誤的執行引發
TERM(15)終止,
-
例子
#! /bin/sh
trap 'rm -f /root/hani/myfile_KaTeX parse error: Expected group after '_' at position 45: …oot/hani/myfile_̲
date > /root/hani/myfile_$$
echo "press ctrl+c to interrupt "
while [ -f /root/hani/myfile_$$ ]; do
echo file exists
sleep 1
done
echo the file no longer exitsts
trap INT
echo creating file /root/hani/myfile_KaTeX parse error: Expected group after '_' at position 27: …oot/hani/myfile_̲
echo "press ctrl+c to interrupt "
while [ -f /root/hani/myfile_$$ ]; do
echo file exists
sleep 1
done
echo we never get here
exit 0
-
結果
[email protected] hani]# ./trap
creating file /root/hani/myfile_4546
press ctrl+c to interrupt
file exists
file exists
file exists
^Cthe file no longer exitsts
creating file /root/hani/myfile_4546
press ctrl+c to interrupt
file exists
file exists
file exists
^C
[[email protected] hani]#
3. unset 指令
從環境中删除變量或函數
#! /bin/sh
foo="hello hani"
echo $foo
unset foo
echo $foo
[[email protected] hani]# ./unset
hello hani
[[email protected] hani]#
4. find 指令
用于搜尋檔案
-
文法:
find [path] [option] [tests] [actions]
[path] 路徑,如 . / /bin 等目錄 或者多個目錄一起 find /etc /home -name abc.txt
-
例子
按照檔案名字查找
find / -name abc.txt 在根目錄下查找檔案 abc.txt
find /etc -name abc.txt 在etc目錄下查找檔案 abc.txt
find /etc -name “abc*” 在etc目錄下查找檔案 abc開頭的檔案
這裡“” ‘’ 都可以
find . -name abc.txt 在目前目錄下查找檔案 abc.txt
find / -mount -name abc.txt 在根目錄,但除了mount 下查找 abc
find . -newer def -type f 在目前目錄下查找比檔案 def 要新的檔案
find . -newer trap -type f 隻查找 檔案類型為c。c為目錄和普通檔案
[[email protected] hani]# find . -newer trap
.
./unset
./myfile_4521
./myfile_4546
[[email protected] hani]#
[[email protected] hani]# find . -newer trap -type f
./unset
./myfile_4521
./myfile_4546
[[email protected] hani]#
5. grep 指令
General Regular Expression Parser 通用正規表達式解析器 grep
在檔案中搜尋字元串
6. 指令的執行
執行一條指令,并把該指令的輸出放到一個變量中。
#!/bin/sh
echo the current directory is $PWD
echo the current users are $(who)
exit 0
[[email protected] hani]# ./mingling.sh
the current directory is /root/hani
the current users are root tty1 2020-06-08 17:04 root pts/0 2020-06-08 17:04 (172.16.255.100)
[[email protected] hani]#
6.1 算術擴充
#!/bin/sh
x=0
while [ "$x" -ne 10 ]; do
echo $x
x=$(($x+))
done
exit 0
[[email protected] hani]# ./suanshukuozhan.sh
0
1
2
3
4
5
6
7
8
9
[[email protected] hani]#
7. here 文檔
在shell腳本程式中向一條指令傳遞輸入的一種特殊方法就是使用here文檔。