shell脚本循环语句

条件判断:if语句

语法格式:
if [ expression ]
then
Statement(s) to be executed if expression is true
fi

注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。

if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if … else 语句:

if ... fi 语句
if ... else ... fi 语句
if ... elif ... else ... fi 语句

实例:

#!/bin/bash/
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater to b"
else
echo "a is less to b"
fi
if ... else 语句也可以写成一行,以命令的方式来运行:
a=10;b=20;if [ $a == $b ];then echo "a is equal to b";else echo "a is not equal to b";fi;

if … else 语句也经常与 test 命令结合使用,作用与上面一样:

#!/bin/bash/
a=10
b=20
if test $a == $b 
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi

分支控制:case语句

case … esac 与其他语言中的 switch … case 语句类似,是一种多分枝选择结构。

示例:

++

对比看就很容易理解了。很相似,只是格式不一样。

需要注意的是:

取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。

取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。
需要注意的是:

取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。

取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。

再举一个例子:

#!/bin/bash
option="${1}"
case ${option} in
"-f") FILE="${2}"
echo "File name is $FILE"
;;
"-d") DIR="${2}"
echo "Dir name is $DIR"
;;
*) 
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac

运行结果:

$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
./test.sh -f index.html
File name is index.html

这里用到了特殊变量${1},指的是获取命令行的第一个参数。
for循环

shell的for循环与c、php等语言不同,同Python很类似。下面是语法格式:

for 变量 in 列表
do
command1
command2
...
commandN
done

示例:

#!/bin/bash/
for value in 1 2 3 4 5
do
echo "The value is $value"
done
输出:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
顺序输出字符串中的字符:
for str in 'This is a string'
do
echo $str
done
运行结果:

This is a string

遍历目录下的文件:
#!/bin/bash
for FILE in *
do
echo $FILE
done

上面的代码将遍历当前目录下所有的文件。在Linux下,可以改为其他目录试试。

遍历文件内容:
city.txt

beijing
tianjin
shanghai
#!/bin/bash
citys=`cat city.txt`
for city in $citys
echo $city
done

输出:

beijing
tianjin
shanghai
while循环

只要while后面的条件满足,就一直执行do里面的代码块。

其格式为:

while command
do
Statement(s) to be executed if command is true
done

命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。
示例:

#!/bin/bash
c=0;
while [ $c -lt 3 ]
do
echo "Value c is $c"
c=`expr $c + 1`
done

输出:

Value c is 0
Value c is 1
Value c is 2

这里由于shell本身不支持算数运算,所以使用expr命令进行自增。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值