2019年7月24日星期三(shell编程)
一、shell循环结构while循环、until循环、for循环 1. until循环与while循环非常相似 while循环?? -> 当什么什么条件成立时,就做循环体的内容。 until循环?? -> 直到什么什么条件成立时,就不做循环体的内容。 2. 框架until 判定条件(测试语句) do? //循环体 ?????? xxxx; done ?? 练习1:使用until循环打印1~100的值出来。 declare -i n=1 until [ $n -gt 100 ] do ?????? echo $n ?????? n=$n+1 done ?? 练习2:研究until的死循环。 #!/bin/bash declare -i n=1 until [ $n -gt 100 ] do ?????? n=1 done 2. for循环1)框架for 变量 in 内容(使用空格分开) do //循环 ?????? xxxx done 2)举实例#!/bin/bash str="hello world apple tree" for n in $str do ?????? echo $n done 结果: ? 练习2: 使用for循环实现将所有的命令行参数都打印出来。 #!/bin/bash declare -i num=1 for n in $* do ?????? echo "argv[$num]:$n" ?????? num=$num+1 done 二、shell函数1)在shell中,函数与C语言函数非常相似,都是用于封装内容,但是使用方式比C语言简单。C语言例子: int fun(char *p1,char *p2) { ?????? printf("p1 = %sn",p1); ?????? printf("p2 = %sn",p2); ?????? return 0; } int main() { ?????? int ret; ?????? ret = fun("hello","world"); ?????? printf("ret = %dn",ret); ?????? return 0; } 2)shell函数里面不需要使用形式参数,使用$1,$*这些来调用形式参数。fun() { ?????? $1? -> 第一个形式参数 ?????? $*? -> 所有的形式参数 } $*?? -> 所有的命令行参数 $1?? -> 第一个命令行参数 3)shell函数框架函数的定义 fun()? -> 在括号中不需要写任何的东西 { ?????? //函数体 ?????? $1? -> 第一个形式参数 ?????? return x?? -> 默认返回值是整型,不需要在函数名前面加返回值的类型 } 函数的调用 fun hello world?? -> 调用fun这个函数,并且传递两个参数给fun。 查看返回值: echo $? ? 练习3: 写一个函数,将传递到该函数中的所有实参都输出来,并且该函数返回值10,打印该返回值。 #!/bin/bash fun() { ?????? for n in $* ?????? do ????????????? echo $n ?????? done ?????? return 10 } fun hello world apple tree echo "return value = $?" 三、trap命令? ->? man 1 traptrap命令其实用于捕捉信号,先讲清楚,将来收到什么信号,要做什么事情。 1)使用方法NAME trap - trap signals? -> 捕捉信号 SYNOPSIS trap [action condition ...]? 2)linux信号有哪些?[email?protected]:/mnt/hgfs/GZ1934/05 shell编程/02/code$ kill -l ?1) SIGHUP?? 2) SIGINT???? 3) SIGQUIT?? 4) SIGILL????? 5) SIGTRAP ?6) SIGABRT? 7) SIGBUS??? 8) SIGFPE???? 9) SIGKILL??? 10) SIGUSR1 11) SIGSEGV? 12) SIGUSR2? 13) SIGPIPE??? 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT?????? 17) SIGCHLD? 18) SIGCONT 19) SIGSTOP? 20) SIGTSTP 2) SIGINT 等价于? "ctrl + C" ? 例题: 假设某个shell脚本运行过程中收到SIGINT,就执行某个函数。 #!/bin/bash fun() { ?????? echo "helloworld" ?????? return 0 } trap fun SIGINT?? -> 将来收到SIGINT信号,就执行fun这个函数 n=0 while [ $n -eq 0 ] do ?????? n=0 done (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |