第三章:Shell语句用法

第一节:if判断

1.单分支

if [ 条件 ]
then
    结果
fi

2.双分支

if [ 条件1 ]      
then
    结果1
else
    结果2
fi

3.多分支

if [ 条件1 ]
then
    结果1
elif [ 条件2 ]
then
    结果2
elif [ 条件3 ]
then
    结果3
elif [ 条件4 ]
then
    结果4
elif [ 条件5 ]
then
    结果5
else
    结果6
fi

4.if嵌套

if [ 条件1 ]
then
    if [ 条件2 ]    #再满足条件1之后再判断条件2
    then
        结果2
    else
        结果3
    fi
else
    结果4
fi

5.if判断语句案例

案例: 输入两个数字 是否为整数 使用if方式 
#!/bin/bash
read -p "请输入第一个数字:" num1
read -p "请输入第二个数字:" num2
if [ -z $num1 ]
then
   echo "您输入的第一个数字为空"&& exit
elif [ -z $num2 ]
then
   echo "您输入的第二个数字为空"&& exit
elif [[  "$num1" =~ ^[0-9]+$ && "$num2" =~ ^[0-9]+$ ]]
then

if [ $num1 -lt $num2 ]
then
   echo "$num1<$num2"
elif [ $num1 -gt $num2 ]
then
   echo "$num1>$num2"
else
   echo "$num1=$num2"
fi

else
    echo "您输入了错误的值!"&& exit
fi    

第二节:for循环

1.for语句格式

for 变量名 in [取值列表]
do
    循环体
done

[root@m01 /scripts]# cat 02for.sh 
#!/bin/bash
IFS=' :.'  #for循环默认以空格为分隔符,来读取数据,这里指定 :. 为分隔符
for i in $(cat /etc/hosts);do
    echo $i
done

2.for嵌套循环

for 变量名 in [取值列表]
do
    for 变量名 in [取值列表]    
    do                       
        循环体
    done
done

第三节:while循环

1.用法一:while后面接条件语句

while [ 条件表达式 ]
do
    循环体
done

2.用法二:while按行读取文件内容

while read line
do
    循环体
done<文件名

第四节:流程控制语句

1.exit 退出整个脚本 不会继续执行
2.break 跳出本次循环 继续往下执行 跳出循环体
3.continue 结束当前此次的命令,继续下一次循环
4.continue 2 结束当前此次的命令,继续循环体下面的命令

第五节:case 流程控制语句

case 变量名4 in
            模式匹配1)
                命令的集合
                    ;;
            模式匹配2)
                命令的集合
                    ;;
            模式匹配3)
                命令的集合
                    ;;
            *)                  *的下一行不需要有;;
            echo USAGE[$0 1|2|3]
esac        

第六节:函数

1.函数定义的三种方式

test1(){
    echo "第一种函数定义方式"
}
function test2(){
    echo "第二种函数定义方式"
}
function test3 {
    echo "第三种函数定义方式"
}

第七节:数组

1.普通数组 只能以数字作为索引(下标)

第一种定义方式
数组名[索引]=值
[root@web scripts]# array[0]=shell
[root@web scripts]# array[1]=Linux
[root@web scripts]# array[2]=MySQL
第二种定义方式 一次定义多个值
数组名=(值)
[root@web02 ~]# array=(shell mysql [20]=kvm [50]=test)
declare -a    #查看普通数组

1.select定义一个菜单

#!/bin/bash
main=(
nginx
tomcat
php
)
select i in ${main[*]}
do
    echo $i
done

2.关联数组 可以使用数字也可以使用字符串作为索引(下标)

declare -A array      #关联数组需要先定义再使用
[root@web02 ~]# array[index1]=Shell
[root@web02 ~]# array[index2]=Linux
[root@web02 ~]# array[index3]=MySQL

3.遍历数组

查看数组的索引,值,和索引个数
1. echo ${array[*]}     #遍历数组的值
2. echo ${!array[*]}    #遍历索引
3. echo ${#array[*]}    #查看索引个数
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容