Linux入门第五天——shell脚本入门(中)基础语法之判断与条件

一、判断式

  利用 test 命令进行执行结果的判断(例如判断是否存在该文件):关于test  testtest

  示例:结合回传值 $? 进行判断:关于$?:$?

[root@localhost tmp]# test -e add.sh;echo $?
0
[root@localhost tmp]# test -e ad1d.sh;echo $?
1
[root@localhost tmp]# test -f add.sh;echo $?
0
[root@localhost tmp]# test -d add.sh;echo $?
1

  更多选项,请参考test给出的参考连接手册!

  当然,以下方式也是可以的:

test -e /dmtsai && echo "exist" || echo "Not exist"

   练习:   

  1. 这个文件是否存在,若不存在则给予一个“Filename does not exist”的讯息,并中断程序;  

  2. 若这个文件存在,则判断他是个文件或目录,结果输出“Filename is regular file”或“Filename is directory”

  3. 判断一下,执行者的身份对这个文件或目录所拥有的权限,并输出权限数据!

   // 注意 && || 的使用方式,注意变量的使用方式${},在shell中执行命令,可以使用$(command)或者反引号亦可!

#!/bin/bash
#function:
#       根据使用者输入的文件名,判断文件是否存在,且给出类型
#author:
#       jiangbei on 2o17/12/15
read -p "input the filename:" filename
test -e ${filename} || echo "file not exists"
test -f ${filename} && filetype="file"
test -d ${filename} && filetype="dir"
test -r ${filename} && perm="r"
test -w ${filename} && perm="${perm}w"
test -x ${filename} && perm="${perm}x"
echo "the filetype of ${filename} is ${filetype}"
echo "the permisstion is ${perm}"

  当然,除了test之外,还可以使用中括号[]来进行判断,参考https://www.cnblogs.com/china1/p/5935999.html

[ "$name1" = "hello world" ]

 

   并且,shell还内置了很多内置变量,如参考连接所示http://blog.csdn.net/c289054531/article/details/9195913

   $n           $1 表示第一个参数,$2 表示第二个参数 ...
   $#           命令行参数的个数
   $0           当前程序的名称
   $?           前一个命令或函数的返回码,返回0代表成功
   $*            以"参数1 参数2 ... " 形式保存所有参数
   $@          以"参数1" "参数2" ... 形式保存所有参数
   $$           本程序的(进程ID号)PID

  测试内置变量如上:

#!/bin/bash
#function:
#       test paras
echo "the script name is ${0}"
echo "total para num is $#"
echo "the whole para is $@"
echo "the first para is ${1}"
echo "the second para is ${2}"

  结果:

[root@localhost tmp]# ./paras.sh p1 p2
the script name is ./paras.sh
total para num is 2
the whole para is p1 p2
the first para is p1
the second para is p2

  参数支持使用shift偏移,参考https://www.cnblogs.com/sunfie/p/5943753.html

二、条件判断式

  1.简单条件判断式——if-then

if [ 条件判断式 ]; then
当条件判断式成立时,可以进行的指令工作内容;
fi <==将 if 反过来写,就成为 fi 啦!结束 if 之意!

  // 中括号的用法参见上文(仔细参考,例如引号与空格的使用!)

  示例:中括号请在左右保持空格,详细参考上文!——中括号支持 [ op1 -o op2 ] 或 [ ] || [ ] 两种形式!

#!/bin/bash
#介绍与作者略
read -p "please input (Y/N):" yn
if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then
        echo "OK,continue"
        exit 0
fi
if [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then
        echo "Oh,interrupt"
        exit 0
fi
echo "unknow command!" && exit 0

   2.带else的判断

# 一个条件判断,分成功进行与失败进行 (elseif [ 条件判断式 ]; then
当条件判断式成立时,可以进行的指令工作内容;
else
当条件判断式不成立时,可以进行的指令工作内容;
fi

  更加复杂的判断:

# 多个条件判断 (if ... elif ... elif ... else) 分多种不同情况执行
if [ 条件判断式一 ]; then
当条件判断式一成立时,可以进行的指令工作内容;
elif [ 条件判断式二 ]; then
当条件判断式二成立时,可以进行的指令工作内容;
else
当条件判断式一与二均不成立时,可以进行的指令工作内容;
fi

  示例:

#!/bin/bash
#略
if [ "$1" == "hello" ]; then
        echo "hello world!"
elif [ "$1" == "" ];then
        echo "please input the arg"
else
        echo "your input is not hello"
fi

   // 声明变量的declare,参见:http://linux.51yip.com/search/declare

  3.case多重分支

   就像之前程序的switch类似,不再赘述功能,看语法:

case $变量名称 in <==关键字为 case ,还有变量前有钱字号
"第一个变量内容") <==每个变量内容建议用双引号括起来,关键字则为小括号 )
程序段
;; <==每个类别结尾使用两个连续的分号来处理!
"第二个变量内容")
程序段
;;
*) <==最后一个变量内容都会用 * 来代表所有其他值
不包含第一个变量内容与第二个变量内容的其他程序执行段
exit 1
;;
esac <==最终的 case 结尾!“反过来写”思考一下!

  

case $变量名 in
 模式1)
 命令序列1
 ;;
 模式2)
 命令序列2
 ;; 
 *)
 默认执行的命令序列     
 ;; 
esac

  示例:

#!/bin/bash
#略
case ${1} in
        "hello")
        echo "hello world"
        ;;
        "hehe")
        echo "hehe"
        ;;
        *)
        echo "error!"
        ;;
esac

  结果:

  

  注意上面语法写的是模式,支持正则:

#!/bin/bash
read -p "press some key ,then press return :" KEY
case $KEY in
[a-z]|[A-Z])
echo "It's a letter."
;;
[0-9]) 
echo "It's a digit."
;;
*)
echo "It's function keys、Spacebar or other ksys."
esac

  提示用户只能指定输入:

case ${num} in
        "one")
        echo "you choose one"
        ;;
        "two")
        echo "you choose two"
        ;;
        "three")
        echo "you choose three"
        ;;
        *)
        echo "Usage ${0} {one|two|three}"
        ;;
esac

  4.使用function()进行函数封装

  要注意的是,因为 shell script 的执行方式是由上而下,由左而右, 因此在 shell script 当中的function 的设置一定要在程序的最前面, 这样才能够在执行时被找到可用的程序段喔 (这一点与传统程序语言差异相当大!初次接触的朋友要小心!)!

  语法:

function fname() {
程序段
}

  直接使用函数名即可引用!

#!/bin/bash
#略
function print(){
        # -n可以不换行
        echo -n "you choose "
}
read -p "input one or two or three" num
case ${num} in
        "one")
        # tr此处用于大小写转换
        print;echo ${num} | tr 'a-z' 'A-Z'
        ;;
        "two")
        print;echo ${num} | tr 'a-z' 'A-Z'
        ;;
        "three")
        print;echo ${num} | tr 'a-z' 'A-Z'
        ;;
        *)
        echo "Usage ${0} {one|two|three}"
        ;;
esac

  另外,函数也支持类似$0 $1等内置变量

另外, function 也是拥有内置变量的~他的内置变量与 shell script 很类似, 函数名称代表示
$0 ,而后续接的变量也是以 $1, $2... 来取代的~ 这里很容易搞错喔~因为“ function
fname() { 程序段 } ”内的 $0, $1... 等等与 shell script 的 $0 是不同的。

  示例:

function printit(){
echo "Your choice is ${1}" # 这个 $1 必须要参考下面指令的下达
}
echo "This program will print your selection !"
case ${1} in
"one"**printit 1** # 请注意, printit 指令后面还有接参数!
;;
"two"**printit 2**
;;
"three"**printit 3**
;;
*echo "Usage ${0} {one|two|three}"
;;
esac
View Code

   另外,传递参数时,必须使用$,也就是使用 fun $arg的形式,而不能使用 fun arg!注意变量的使用方式!第二种方式被认为是传递arg这个字符!

posted @ 2017-12-15 14:24  ---江北  阅读(337)  评论(0编辑  收藏  举报
TOP