Shell 脚本 if条件语句,for循环,case语句

(1)case语句是用来实现多个if..else的功能的,case会对字符串进行匹配,是从第一个模式开始的,如果有一个模式已经匹配成功的话,其他的模式就不会再进行匹配了。

#!/bin/sh
echo "please yes or no"
read input
 
#case语句的基本用法,记住每一个匹配后边都有双分号,代表本模式的结束和下一个#模式的开始,在进行通配符匹配的时候不要加双引号
case "$input" in
yes ) echo "yes" ;;
y* ) echo "y*" ;;
y ) echo "y" ;;
no ) echo "no" ;;
n ) echo "n" ;;
* ) echo "default" ;;
esac
 
#合并匹配模式,case的匹配只能匹配一条,想要做到匹配多个结果使用如下的方式
case "$input" in
y* | Y* ) echo "yes" ;;
n* | N* ) echo "no" ;;
* ) echo "default" ;;
esac
 
#一种更屌的匹配
case "$input" in
[yY][eE][sS] | [yY] ) echo "yes" ;;
[nN] | [nN][oO] ) echo "no" ;;
* ) echo "default"
echo "end"
esac
 
exit 0

(2)shell编程使用到的循环语句,包括for循环,while循环,until循环,for后边跟一个变量,然后是一个集合,将集合中的东西赋给这个变量,每次循环执行,while循环和if使用同样的条件判断,满足条件执行语句,until和while相反,不满足条件执行语句。

#!/bin/sh
#for循环最基本的用法
for var in "hello" "lily" "welcome"
do
echo -n "$var "
done

echo

#通配符扩展
for var in $(ls *.sh)
do
echo "$var"

done

#while循环,后边和if一样跟的都是条件
echo "please input secret"
read secret
while [ "$secret" != "lily" ]
do
echo "try again"
read secret
done

#until循环和while相反,条件为假才执行
echo "please input text"
read text
until [ "$text" = "xiao ta" ]
do
echo "try again"
read text
done

exit 0

(3)条件语句if的用法

#!/bin/sh
echo "please input text1"
read text1
echo "please input text2"
read text2
#判断字符串等或者是不等只有一个等号
if test $text1 = $text2
then
echo "text1 equals text2"
else
echo "text1 not equals text2"

fi

#判断字符串是否为空,这里的判断记得在$text1俩边加上双引号
if [ -z "$text1" ]
then
echo "text1 is null"
fi
if [ -n "$text1" ];then
echo "text1 is not null"

fi

#算术比较 text1和text2中的内容只能是数字
if [ "$text1" -eq "$text2" ];then
echo "equal"
elif [ "$text1" -gt "$text2" ];then
echo "great"
elif [ "$text1" -le "$text2" ];then
echo "little and equals"

fi

echo "input a file or not file"
read file
#判断是文件还是目录
if [ -d $file ];then
echo "$file is a directory"
elif [ -f $file ];then
echo "$file is a file"

fi

#判断文件的大小是否为空
if [ -s $file ];then
#echo -n是为了去掉换行符
echo -n "$file'size is not null"

fi

#判断文件的读写权限
if [ -f "$file" ];then
 if [ -r "$file" ];then
 echo "read"
 fi
 if [ -w "$file" ];then
 echo "write"
 fi
 if [ -x "$file" ];then
 echo "exe"
 fi
fi

exit 0

echo后边的字符串最好用双引号引起来,以后凡是字符串最好都用双引号引起来,这可以避免一些很难查找到的bug

不同引号对变量的作用:

双引号"":可解析变量,$符号为变量前缀。

单引号'':不解析变量,$为普通字符。

反引号``:将命令执行的结果输出给变量。


原文链接:http://www.jb51.net/article/55030.htm


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值