shell 编程5 分支语句

1 if

格式:

if [ 表达式 ]
    then
    //操作语句
    else 
    //操作语句
fi

多分支语句:

if [ 表达式 ]
    then
    //操作语句
elif
    then
    //操作语句
    else 
    //操作语句
fi

示例:

1.判断是否是root用户

#!/bin/bash

curr_user=$(env | grep "USER" | cut -d "=" -f 2)
if [ "${curr_user}" == "root" ];
        then
                echo  "current login is root"
        else echo "current login is not root ,is ${curr_user}"
fi

2.判断磁盘是否占满

#!/bin/bash
disk_use=$(df | grep sda1 | awk '{print $5}' | cut -d "%" -f 1)
if [ "${disk_use}" -ge "10" ]
	then
		echo 'warning,disk_user greater than 10%'
fi

3.判断是否是文件夹

#!/bin/bash
read -p "please input you directory: " dir

if [ -d "${dir}" ]
	then 
		echo "you input is directory"
	else 
		echo "you input is not  directory"
fi

exit:终止当前脚本,后 可以加返回值。

if [ "1" == "1" ]
    then
        exit 1
fi

4 判断文件类型:

#!/bin/bash
read -p "please file path: " path

if [ -n "${path}" ]
	then 
	if [ -e "${path}" ]
		then
		if [ -f "${path}" ]
			then 
				echo "file"
		elif [ -d "${path}" ]
			then echo "directory"
		else echo "other file"
		fi
	else echo "path is not exist"
	fi
else echo "path is null"
fi

case:

语法:

case $变量名 in
  "值1")
       如果变量值等于值1,执行程序1
       ;;
  "值2")
       如果变量值等于值2,执行程序2
       ;;
  ……
  ……
   *)
      如果变量值都不是以上值,则执行此程序
      ;;
esac

;; 类似break

示例: 判断输入的是yes 还是no

read -p "please input yes/no: " input
case "$input" in
        "yes")
                echo "right"
        ;;
        "no") echo "error"
        ;;
        *)
                echo "input yes/no"
esac

3 for 循环

语法:

for循环语法一:<br>
for 变量 in 值1 值2 值3…<br>
    do
         程序
done

示例:

批量输出文件名:

cd /home/quan/shell
ls >>a.log
for i in $(cat a.log)
        do
                echo "${i}"
        done
rm -rf a.log

循环打印

for((i=0;i<10;i=i+1))
	do
	echo "${i}"
	done

4 while循环

格式:

while [ 条件判断式 ]
    do
        //操作
    done

示例:

#!/bin/bash
i=0
s=0
while [ $i -le 100 ]
do
        s=$(($i + $s))
        i=$(($i + 1))
done
echo $s

5 until

格式:

until [ 表达式 ]
do
//操作
done

示例:

i=0
s=0
until [ $i -gt 100 ]
do
        s=$(($i + $s))
        i=$(($i + 1))
done
echo $s

在循环中可以通过break和continue来进行循环的跳出

猜你喜欢

转载自blog.csdn.net/qq_39158142/article/details/83719599
今日推荐