本節主要内容
- shell腳本調試
- shell函數
- shell控制結構初步
1. shell腳本調試
當腳本出錯時,需要對腳本進行調試,學會腳本調試是每個linux系統使用者必備技能。shell腳本調試無需任何額外的工具,隻需要要在腳本檔案前加-x選項即可,建立debug.sh檔案,内容如下:
#!/bin/bash
#Filename: debug.sh
echo "scripting"
echo "debuging"
ls +
使用bash -x 指令進行腳本調試
root@sparkslave02:~/ShellLearning/Chapter12# bash -x debug.sh
+ echo scripting
scripting
+ echo debuging
debuging
+ ls +
ls: cannot access +: No such file or directory
-x選項将shell腳本每一行指令及執行結果列印輸出,如此便能幫助開發人員快速定位到出錯的腳本位置。如果代碼量比較大或者腳本開發人員知道代碼出錯的大緻位置,則可以使用set -x; set +x;指令進行局部調試,如
#!/bin/bash
#Filename: debug2.sh
for i in {..}
do
set -x
//set -x表示跟在該指令後的腳本輸出調試資訊
echo $i
//set +x表示從此處禁用調試
set +x
done
echo "Script executed"
上面的代碼意味着,隻會列印輸出echo $i,具體調試資訊輸出如下:
[email protected]:~/ShellLearning/Chapter12# ./debug2.sh
+ echo
+ set +x
+ echo
+ set +x
+ echo
+ set +x
+ echo
+ set +x
+ echo
+ set +x
+ echo
+ set +x
除bash -x指令進行腳本調試之外,還可以在腳本的第一行添加-xv指令,使得腳本預設進行調試,例如:
//加-xv選項,使腳本執行時會列印輸出調試資訊
#!/bin/bash -xv
#Filename: debug.sh
for i in {..}
do
set -x
echo $i
set +x
done
echo "Script executed"
~
2. shell函數
同樣,同c、c ++等程式設計語言一樣,shell中可以定義函數,函數的定義格式如下
function fname()
{
shell腳本語句;
}
vim指令建立functionDemo.sh腳本檔案
root@sparkslave02:~/ShellLearning/Chapter12# vim functionDemo.sh
#定義一個函數fname
function fname(){
#輸出第一個參數
echo $1
#輸出函數所在檔案名
echo $0
#輸出所有參數
echo $@
}
#将函數中傳入兩個參數
fname "arg1" "args"
執行結果:
root@sparkslave02:~/ShellLearning/Chapter12# ./functionDemo.sh
arg1
./functionDemo.sh
arg1 args
3. shell控制結構初步
同其它程式設計語言一樣,shell也有自己的控制結構,包括for循環、while循環、until循環,if語句等。本小節先介紹for循環的使用,for循環的用法非常多,下面給出四個最為常用的for循環用法
(1)for i in $(seq 10)
root@sparkslave02:~/ShellLearning/Chapter12# vim forloop.sh
for i in $(seq )
do
echo $i
done
root@sparkslave02:~/ShellLearning/Chapter12# chmod a+x forloop.sh
root@sparkslave02:~/ShellLearning/Chapter12# ./forloop.sh
(2) for((i=1;i<=10;i++))
for((i=;i<=;i++))
do
echo $i
done
(3)for i in ls
ls
root@sparkslave02:~/ShellLearning/Chapter12# vim forloop3.sh
for i in `ls`
do
echo $i
done
root@sparkslave02:~/ShellLearning/Chapter12# chmod a+x forloop3.sh
root@sparkslave02:~/ShellLearning/Chapter12# ./forloop3.sh
debug2.sh
debug.sh
forloop2.sh
forloop3.sh
forloop.sh
functionDemo.sh
(4)for i in ${arr[*]}
root@sparkslave02:~/ShellLearning/Chapter12# vim forloop4.sh
arr=( )
for i in ${arr[*]}
do
echo ${arr[i]}
done
root@sparkslave02:~/ShellLearning/Chapter12# ./forloop4.sh