Linux学习之Shell中if-else

在Shell脚本中,if-else使用方法如下:

if [测试条件]
then 
       测试条件成立执行
else
       条件不成立执行
fi

cat << CCC >> testIfElse.sh表示只有遇到CCC才结束往testIfElse.sh写入文件。<< CCC表示后续的输入作为子命令或者子Shell的输入,直到命令又遇到CCC,再次返回到主调Shell,可将CCC其理解为分界符(delimiter),当然在不与系统其他命令冲突的话,可以定义其他分界符,比如EOFDelimiterEnd等。
下边的内容每输入一行就按一下回车键:

#!/bin/bash
if test 6 -gt 5
then
     echo "6 > 5"
else
     echo "wrong"
fi
CCC

Linux学习之Shell中if-else_第1张图片
chmod 777 testIfElse.sh为所有的用户加上读写执行权限,./testIfElse.sh进行执行。
在这里插入图片描述

只要写在thenelse之间的语句都是测试条件正确应该执行的,而写在elsefi之间都是测试条件错误应该执行的语句。
testIfElse1.sh里边的内容如下:

#!/bin/bash
# test with variable


echo "name ${0}"
echo "variable's number is $#"
echo "first variable is $1"

if [ $# -eq 2 ]
then
   echo "variable's number = 2"
   echo "the second variable is $2"
else
   echo "variable's number is not two"
   echo "wrong"
fi

Linux学习之Shell中if-else_第2张图片
这段代码首先把name +程序名输出,然后把variable's number is +输入的变量个数输出,之后输出first variable is +第一个变量名输出,上边的输出不管测试条件是否正确都会输出。
测试条件正确的话(即输入的变量个数等于2)会输出:

variable’s number = 2
the second variable is 第二个变量名

测试条件错误的话会输出:

variable’s number is not two
wrong

chmod 777 testIfElse1.sh为所有的用户加上读写执行权限,./testIfElse1.sh good learn进行执行输出内容如下:

name ./testIfElse1.sh
variable's number is 2
first variable is good
variable's number = 2
the second variable is learn

./testIfElse1.sh good learn "make progress"执行输出的内容如下:

name ./testIfElse1.sh
variable's number is 3
first variable is good
variable's number is not two
wrong

Linux学习之Shell中if-else_第3张图片
要是测试条件分支比较多的话,那么可以使用底下的格式:

if [测试条件]
then 
       测试条件成立执行
elif [测试条件]
then
		测试条件成立执行
else
       条件不成立执行动作
fi

testIfElse2.sh里边的内容如下:

#!/bin/bash
# test with variable


echo "name ${0}"
echo "variable's number is $#"
echo "first variable is $1"

if [ $# -eq 2 ]
then
   echo "variable's number = 2"
   echo "the second variable is $2"
elif [ $# -eq 3 ]
then
    echo "variable's number = 3"
    echo "the second variable is $3"
else
   echo "variable's number is not two"
   echo "wrong"
fi

基本逻辑就跟上边testIfElse1.sh一样,但是多了一段elif的判断逻辑,就是若输入的变量个数等于3的话,就会输出:

variable’s number = 3
the second variable is 第三个变量名

Linux学习之Shell中if-else_第4张图片

chmod 777 testIfElse2.sh为所有的用户加上读写执行权限,./testIfElse2.sh 111 222的执行结果如下:

name ./testIfElse2.sh
variable's number is 2
first variable is 111
variable's number = 2
the second variable is 222

Linux学习之Shell中if-else_第5张图片

./testIfElse2.sh 111 222 333的执行结果如下:

name ./testIfElse2.sh
variable's number is 3
first variable is 111
variable's number = 3
the second variable is 333

Linux学习之Shell中if-else_第6张图片

./testIfElse2.sh的执行结果如下:

name ./testIfElse2.sh
variable's number is 0
first variable is
variable's number is not two
wrong

Linux学习之Shell中if-else_第7张图片

此文章为7月Day 23学习笔记,内容来源于极客时间《Linux 实战技能 100 讲》。

你可能感兴趣的:(Linux基础学习,linux,学习)