🔥个人主页 🔥
😈所属专栏😈
目录
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