微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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的用法

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" ]
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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐