shell编程基础(3)条件判断语句

来源:互联网 发布:管理数据的重要性 编辑:程序博客网 时间:2024/05/14 01:49

1,带参数的shellscript

#this is program build 5.11 to test shell script############  cxz  #######    5.11  ############echo "you have given $0 $# argument"echo "the argument you give is \n $@"

#$0表示所执行的shellscript $#表示shellscript 所带的参数总数

[ $# -lt 2 ]&&echo "the num of argument is less than 2"&&exit 0

# $# -lt 2表示的是参数总数小于2,注意方括号的空格关系,$#之前和2之后都要有空格

echo "the first argument is $1"echo "the second argument is $2"shift 1

#shift是移位指令,作用是将“第n个参数”往后移动,shift 1则把“第一个参数”个称呼向后移动一个,这个称呼落在了第二个参数上

echo "the fist argument after shift is $1"

上面的程序简单的使用了shellscript 与参数协作,通过shellscript与参数写作,可以通过参数来触发程序中不同的功能

2.条件判断语句

#################This is the program to test if & else ###########  cxz  ###########   5.11   ###############read -p "please type in the Y/N   " ynif [ "$yn" == "y" ] || [ "$yn" == "Y" ];then    echo "the answer is yes"

#if语句在Linux中用来判断,和c++中不同,if判断条件后加了;if和[之间必须要有个空格,如果不加这个空格的话,会导致错误”unexpect then, expecting fi”。
#[]中==前后必须加上空格,否则会导致无论怎么判断都执行the answer is yes.

elif [ "$yn" == "n" ] || [ "$yn" == "N" ];then    echo "the answer is no"else     echo "the answer is unknow"fi

#if 的结尾要带上fi,感觉程序员都是萌萌哒

在使用判断语句的时候,最重要的就是[]有关的空格。一定要注意

0 0
原创粉丝点击