Linux shell脚本编程入门(二) 循环语句


前面有了变量的概念和逻辑运算符,就可以写判断语句了,不过这里注意中括号的两边必须得留空格,不然报错.

运算符

  • 赋值, 用 let 语句, 如 let "a=1"
  • 算数运算, 支持 +  -  *  /  %(模运算)  **(幂运算)
  • 位运算符, 支持 <<(左移)  >>(右移)  &(按位与)  |(按位或)  ~(按位取反)  ^(按位异或)   

if / then / else 语句

先举个栗子呗~

#!/bin/bash

read var1

if [ "$var1" -gt 15 ]
then
	echo "$var1 is greater than 15"
else 
	echo "$var1 is less than 15"
fi

注: 听说如果 else 里面又嵌套一个 if 语句,可以考虑用 elif 语句,这样子可以减少 fi 的数量,使得结构清晰


case 语句

#!/bin/bash

read day

week=(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)

case $day in
	1)
		echo ${week[1]};;
	2)
		echo ${week[2]};;
	3)
		echo ${week[3]};;
	4)
		echo ${week[4]};;
	5)
		echo ${week[5]};;
	6)
		echo ${week[6]};;
	7)
		echo ${week[0]};;
	*)
		echo "no such day...";;
esac


for循环

下面写了四种格式,貌似还有别的

#!/bin/bash

for var1 in Mon Tue Wed Thu Fri Sat Sun
do 
	echo "Today is $var1 "
done

for var2 in {1..10..2}
do
	echo "This is $var2"
done

for var3 in $(seq 1 2 10) 
do
	echo "I have a/an $var3"
done

for var4 in $(ls)
do
	echo "Here is the file $var4"
done

while循环

#!/bin/bash

i=1

while (( i <= 5 ))
do
	echo "i = $i"
	let "++ i"
done

select语句

这个select语句到时木有见过,运行的时候可以和用户交互, 运行一下下面的程序就懂了. 注意不加break的话,会死循环下去

#!/bin/bash

echo "Which color do you like?"

select var1 in red green blue
do
	echo "I like $var1"
	break
done

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。