【Linux shell】条件判断和流程控制
🔥个人主页 🔥
😈所属专栏😈
目录
shell中的算术运算
条件判断
两个整数之间的比较,字符串之间的比较
文件权限的判断
文件类型判断
流程控制
if语句
for循环
while循环
switch语句
shell中的算术运算
语法:$(())
#!/bin/bash
read a
read b
num1=$((a + b))
echo "和为$num1"
num2=$((a * b))
echo "积为$num2"
条件判断
两个整数之间的比较,字符串之间的比较
- -lt :小于(less than)
- -le:小于等于(less equal)
- -eq:等于(equal)
- -gt:大于(greater than)
- -ge:大于等于(greater than)
- -ne 不等于(no equal)
#!/bin/bash
read num
if [ $num -lt 25 ];then
echo "$num is smaller than 25"
elif [ $num -eq 25 ];then
echo "$num is equal 25"
elif [ $num -gt 25 ];then
echo "$num is bigger than 25"
fi
文件权限的判断
- -r:读的权限
- -w 写的权限
- -x 执行的权限
#!/bin/bash
echo $1
if [ -r $1 ];then
echo "the file has the access of read"
fi
if [ -w $1 ];then
echo "the file has the access of write"
fi
if [ -x $1 ];then
echo "the file has the access of execute"
fi
文件类型判断
- -f 文件存在并且是一个常规的文件
- -e 文件存在
- -d 文件存在并且是一个目录
#!/bin/bash
echo $1
if [ -f $1 ];then
echo "文件存在并且是一个常规的文件"
fi
if [ -e $1 ];then
echo "文件存在"
fi
if [ -d $1 ];then
echo "文件存在并且是一个目录"
fi
流程控制
if语句
语法:
if [ 条件 ];then
#要执行的代码
elif [ 条件 ];then
#要执行的代码
else
#要执行的代码
fi
注意[]中的条件前后都要有空格
for循环
c风格for循环
#!/bin/bash
for ((i=1;i<5;i++));do
echo "current number is $i"
done
遍历命令行参数
for i in "$@";do
echo "arg is $i"
done
遍历数组
p=("zhangsan" "lisi" "wangwu")
for i in "${p[@]}";do
echo "$i"
done
while循环
语法:
while[ 条件 ];do
#循环体
done
echo "please input a number"
read num
aim=24
while true;do
if [ $num -lt $aim ];then
echo "the number you guess is smaller"
read num
elif [ $num -gt $aim ];then
echo "the number you guess is bigger"
read num
elif [ $num -eq $aim ];then
echo "you are right"
break
fi
done
switch语句
语法
case 值 in
1)
echo "选择1"
;;
2)
echo "选择2"
;;
3)
echo "选择3"
;;
*)
echo "无效选择"
;;
esac
示例
read choice
case $choice in
1)
echo "选择功能1"
;;
2)
echo "选择功能2"
;;
3)
echo "选择功能3"
;;
*)
echo "无效选择"
;;
esac
select语句
#!/bin/bash
echo "请选择一个选项:"
select choice in "显示日期" "显示目录内容" "显示当前用户" "退出"
do
case $choice in
"显示日期")
date
;;
"显示目录内容")
ls -la
;;
"显示当前用户")
whoami
;;
"退出")
echo "谢谢使用!"
break
;;
*)
echo "无效选择,请重试"
;;
esac
done
函数
语法:调用函数后使用$?来获取返回值
函数名称(){
函数体
return
}
#调用函数
函数名称 参数1 参数2
无参数有返回值
#!/bin/bash
sum(){
echo "求两个数字的和"
read -p "请输入第一个数字的值" a
read -p "请输入第二个数字的值" b
return $(($a+$b))
}
sum
echo "两个数字的和为 $?"
有参数有返回值
#!/bin/bash
diff(){
echo "求两个数字的差"
return $(($1-$2))
}
diff 9 3
echo "两个数字的差 为 $?"