鳥哥Linux(三)Shell Script && RE摘錄

1.指令測試功能:test
a)測試文件
test -e
test -f
test -d
b)測試文件的屬性
test -r filename
test -w filename
test -x filename:是否可執行
test -s filename:是否爲非空的文件
c)比較兩個文件
test file1 -nt file2: newer than
test file1 -ot file2: older than
test file1 -ef file2: wehther the same file
d)比較兩個整數
test n1 -eq n2
test n1 -ne n2
test n1 -gt n2
test n1 -lt n2
test n1 -ge n2
test n1 -le n2
e)判斷字符串
test -z str: 判讀str是否爲空字符串
test -n str: 判讀str是否爲非空字符串,-n可以省略
test str1=str2
test str1!=str2
f)多重條件判定: test -r filename -a -x filename
-a:同時成立
-o:任何一個成立
!:反向

2.[]代替test:[ "${HOME}" == "${MAIL}" ]

3.shell script的參數
sh spr_name op1, op2, op3 ...
     $0      $1  $2   $3

條件判斷式:
if [ 條件判斷 ]; then
   do sth1
elif
   do sth3
else
   do sth2
fi


case $var in
 "case1")
   do sth1
   ;;
 "case2")
   do sth2
   ;;
 "case3")
   do sth3
 *)
   do oth(do other thing)
   ;;
esac

while [ 條件 ]
do
      sth
done
如果條件成立,就一直循環

until [ 條件 ]
do
      sth
done
如果條件不成立,就一直循環

for ((初始值;限制值;執行步階))
do
   sth
done

for var in con1 con2 con3...
do
   sth
done



function fname() {
     do sth
}
這裏的函數也有參數的概念,也用$0, $1, $2表示



sh [-nvx] scripts.sh

-n:不執行,只檢查語法
-v:執行sh前,先把sh的內容輸出到屏幕上
-x:將使用到的sh內容顯示到屏幕上(用於debug)



Shell Regular Expression:
^:既可以是表示開頭也可以表示非([^a]不等於小寫字幕a)
{}:在shell中使用要轉義, grep -n 'o/{2/}', 列出有2個o出現的次數


擴展的grep(grep -E):
For Example:grep -v '^$' xxx.txt | grep -v '^#' = egrep -v '^$|^#' xxx.txt

+:
?:
|:
():egrep -n 'g(la|oo)d' xx.txt

printf命令:
printf '打印格式' 實際內容


sed -[nefr] [action]:
-n:使用silent模式,只有經過sed處理的行纔會被顯示出來
-e:直接在指令模式上進行sed的動作編輯
-f:
-r:sed的支持延伸正則表達式的語法,默認是基礎正則表達式

[n1[,n2]]action

n1行-n2行,可以沒有

action:
aSTR:add,STR會加在目前行的下一行
cSTR:replace,STR可以取代n1和n2之間的行
d:   delete
iSTR:add,STR會加在目前上的上一行
p:   print,將某個選擇的數據打印到屏幕,
s:   替換,s通常搭配正則表達式,1,20s/old/new/g  (1-20行的所有old替換爲new)

例子:去掉ifconfig得到結果的1-10行,ifconfig | sed '1,10d'


awk:用於處理一個整行,把一行分爲幾個字段來進行。
awk '條件類型1 {動作1} 條件類型2 {動作2}...' filename

每一行中的第一個字庫用$1表示,以此類推,$0表示這一行

awk的內置變量:
NF 每行擁有的字段數
NR awk目前處理的是第幾行
FS 目前的分隔符,默認是空格


文件比較(文本):
diff -[bBi] file1 file2
-b:忽略空格的差異
-B:忽略空白行的差異
-i:忽略大小寫的差異

文件比較(二進制):
cmp [-s] file1 file2
-s:列出所有的不同點,因爲默認只會輸出第一個不同點




expr op1 op op2: 執行一個表達式, expr 3 /* 5, 輸出15

eval:執行shell 命令

shift: 左移一個參數,$2變成$1
date的格式化輸出: date '+%H:%M:%S %Y-%m-%d'

                             date +%s

base path: Print NAME with any leading directory components removed

dirname path: Print NAME with its trailing /component removed; if NAME contains

uname -a: 輸出機器名的詳細信息

echo $$: 輸出本進程(bash)的ID

tee指令會從標準輸入設備讀取數據,將其內容輸出到標準輸出設備,同時保存成文件。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章