Shell指令碼程式設計
1.linux中的變數
linux中的變數分為環境變數和普通變數,其中環境變數可以理解為全域性變數,在所有shell的子程式中都可以引用,普通變數只能在自己的shell程式中使用,程式結束後變數無法保留。
設定環境變數的方法:
1.export命令 使用者退出後失效
export test=12312
2..bash_profile、.bashrc、etc/bashrc或者etc/profile中定義
使用者的環境變數: ls /root/.bashrc(推薦檔案) ls /root/.bash_profile 全域性變數配置 /etc/profile etc/bashrc(推薦) 所有環境變數應該為大寫
檢視環境變數:
env檢視環境變數列表 set 輸出所有變數(包括環境變數和普通變數)
unset消除環境變數
unset $PATH
2.變數定義
本地變數定義三種方法:
a=123+ $a 變數會被解析
a=123 b=123$a echo $b
輸出以下:
a='123 + $a' 變數不會被解析,單引號中的字串原樣輸出
a=123
b='123$a'
echo $b
輸出為:
123$a
a="123" 變數解析--一般用此種方法定義變數
a=123 b="123$a" echo $b
命令結果作為變數的值(常見用法):
a=$(ls)
3.對於字串的操作
輸出字串長度:
name="testName"
方法一:
echo ${#name}
輸出結果:
方法二:
echo ${name}|wc -L
方法三:
expr length "${name}"
擷取字串內容:
首先定義字串:
name=testNametestName
擷取字串:
echo ${name:2} 從第二位開始擷取
輸出結果:
stNametestName
字串匹配
echo ${name#t*N} 從頭開始最短匹配
輸出為:
ametestName
最長匹配:
echo ${name##t*N} 從頭開始最長匹配
輸出為:
ame
從尾開始匹配:
echo${name%N*e}
輸出為:
testNametest
最長匹配:
echo ${name%%N*e}
test
字串的替換:
echo ${name/test/test1} 從頭匹配替換第一個 echo ${name//test/test1} 從頭匹配替換所有
將以下檔名中的all去掉
test-all-1.txttest-all-2.txttest-all-3.txttest-all-4.txttest-all.txt
指令碼為:
for f in $(ls *.txt) do mv ${f} ${f//all/} done
4.算術運算
方法一:
echo $((2+2)) 4
方法二:
let a=12+12 echo ${a} 24
方法三:
expr 12 % 3 0 echo "123 122" |awk '{print ($1-$2)}' $[]echo $[12+12]a=$[12+12+12]
5.條件判斷語句:
方法一:
test test -f test4.txt && echo true || echo false
方法二:
[] [ -f test4.txt ] && echo true || echo false 檔案test4.txt存在輸出true,不存在輸出false
方法三:
[[]] 括號前後加空格 [[ -f test4.txt ]] && echo true || echo false
字串測試:
[ -z "" ] && echo false-z 字串長度為0的時候為真 [ -n "test" ] && echo true || echo false -n 字串長度不為0的時候為真 [ "test" == "test" ] && echo true 字串是否相等 同= != 等號和中括號兩端需要有空格 整數的比較: [ 2 -eq 3 ] && echo true || echo false 邏輯操作符: -a -o ! 與或非 [ 2 -eq 2 -a 3 -eq 3 ] && echo true || echo false
6.if條件語句
單分支結構: if<條件表示式> then 指令 fi if <條件表示式>; then 指令 fi
多分支:
if<條件表示式> then else fi
多分支:
if<條件表示式> then elif<條件表示式> then else fi
7.shell函式
functiontest.sh指令碼內容:
function testFun(){ echo "function test! hello $1"; } testFun $1 sh functiontest.sh testname
while和until迴圈
while<條件表示式> do 命令 done until<表示式> do done
指令碼後臺執行:
sh functiontest.sh& control + c 停止 control + z 暫停
for 語句
for((i=1;i<5;i++)) do echo $i done
select 語句
select name in ywp hf csq do echo $name done
break n 跳出整個迴圈
continue n 跳出本次迴圈
陣列:
array=(ywp hf jc yc)
echo ${array[1]}
方法二:
array=([1]=one [2]=two [3]=threee ) echo ${array[1]} echo ${array[*]} *列印整個陣列的內容
for迴圈列印陣列內容
array=(test1 test2 test3) for name in ${array[*]} do echo ${name} done
動態陣列:
array=($(ls)) echo ${array[*]} echo ${#array[*]} 列印陣列長度
9.shell指令碼開發規範
1.全域性變數 全部大寫 2.區域性變數 駝峰 3.變數引用 ${} 4.字串變數引用 "${}" 5.統一使用.sh命名 6.啟動和停止統一使用start和stop開頭 7.通用變數放在config目錄下 8.中括號兩邊新增空格
shell指令碼除錯:
sh [-nvx] test.sh -n 不執行,僅檢查語法問題 -x將執行的指令碼輸出到螢幕上
vim 配置:
echo 'alias vi=vim' >>/Users/xxx/.bash_profile source /Users/xxx/.bash_profile