本节主要内容1. shell脚本调试
当脚本出错时,,需要对脚本进行调试,学会脚本调试是每个linux系统使用者必备技能。shell脚本调试无需任何额外的工具,只需要要在脚本文件前加-x选项即可,创建debug.sh文件,内容如下:
ls +
使用bash -x 命令进行脚本调试
root+ echo scriptingscripting+ echo debugingdebuging+ ls +ls: cannot access +: No such file or directory
-x选项将shell脚本每一行命令及执行结果打印输出,如此便能帮助开发人员快速定位到出错的脚本位置。如果代码量比较大或者脚本开发人员知道代码出错的大致位置,则可以使用set -x; set +x;命令进行局部调试,如
i in {1..6}doset -x//set -x表示跟在该命令后的脚本输出调试信息echo $i//set +x表示从此处禁用调试set +x
上面的代码意味着,只会打印输出echo $i,具体调试信息输出如下:
root@sparkslave02:~/ShellLearning/Chapter12# ./debug2.sh + + set +x+ + set +x+ + set +x+ + set +x+ + set +x+ + set +x
除bash -x命令进行脚本调试之外,还可以在脚本的第一行添加-xv命令,使得脚本默认进行调试,例如:
//加-xv选项,使脚本执行时会打印输出调试信息i in {1..6}doset -x+x~2. shell函数
同样,同c、c ++等编程语言一样,shell中可以定义函数,函数的定义格式如下
{ shell脚本语句;}
vim命令创建functionDemo.sh脚本文件
rootfunction fname(){ #输出第一个参数 echo $1 #输出函数所在文件名 echo $0 #输出所有参数 echo $@}#将函数中传入两个参数fname “arg1” “args”
执行结果:
rootarg1./functionDemo.sharg1 args3. shell控制结构初步
同其它编程语言一样,shell也有自己的控制结构,包括for循环、while循环、until循环,if语句等。本小节先介绍for循环的使用,for循环的用法非常多,下面给出四个最为常用的for循环用法
(1)for i in $(seq 10)rooti in $(seq 10)doecho $idonerootroot(2) for((i=1;i<=10;i++))for((i=2;i<=10;i++))(3)for i in lsrooti in `ls`doecho $idonerootrootdebug2.shdebug.shforloop2.shforloop3.shforloop.shfunctionDemo.sh(4)for i in ${arr[*]}rootarr=()for i in ${arr[*]}doecho ${arr[i]}doneroot
那里面非常漂亮,个个观景区都能看到奇形怪状的岩石。