码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2015-01-04 23:05:48      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:linux   linux shell   编程   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

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

标签:linux   linux shell   编程   shell   脚本   

原文地址:http://blog.csdn.net/zhangxb35/article/details/42402333

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!