Spark修炼之道(基础篇)——Linux大数据开发基础:第十二节:Shell编程入门(四)...

    xiaoxiao2026-02-18  16

    本节主要内容

    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 {1..6} do set -x //set -x表示跟在该命令后的脚本输出调试信息 echo $i //set +x表示从此处禁用调试 set +x done echo "Script executed"

    上面的代码意味着,只会打印输出echo $i,具体调试信息输出如下:

    root@sparkslave02:~/ShellLearning/Chapter12# ./debug2.sh + echo 1 1 + set +x + echo 2 2 + set +x + echo 3 3 + set +x + echo 4 4 + set +x + echo 5 5 + set +x + echo 6 6 + set +x

    除bash -x命令进行脚本调试之外,还可以在脚本的第一行添加-xv命令,使得脚本默认进行调试,例如:

    //加-xv选项,使脚本执行时会打印输出调试信息 #!/bin/bash -xv #Filename: debug.sh for i in {1..6} 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 10) do echo $i done root@sparkslave02:~/ShellLearning/Chapter12# chmod a+x forloop.sh root@sparkslave02:~/ShellLearning/Chapter12# ./forloop.sh 1 2 3 4 5 6 7 8 9 10

    (2) for((i=1;i<=10;i++))

    for((i=2;i<=10;i++)) do echo $i done

    (3)for i in 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=(0 1 2 3) for i in ${arr[*]} do echo ${arr[i]} done root@sparkslave02:~/ShellLearning/Chapter12# ./forloop4.sh 0 1 2 3 相关资源:python入门教程(PDF版)
    最新回复(0)