LINUX中shell脚本中语句的基本用法
一、if ...then...fi
if [ 条件判断一 ] && (||) [ 条件判断二 ]; then <==if 是起始,后面可以接若干个判断式,使用 && 或 || 执行判断
elif [ 条件判断三 ] && (||) [ 条件判断四 ]; then <== 第二段判断,如果第一段不符合要求就转到此搜寻条件,执行第二段程序
else <==当前两段都不符合时,就执行这段内容
fi <== 结束 if then 的条件判断
上面的意思是:中括号[] 里的是条件表达式,如果是复合条件判断(如若A 及B 则C 之类的逻辑判断),那么就需要在两个中括号之间加&&(and)或| | (or )这样的逻辑运算符。如果是多重选择,那么需要以elif(可选的,需要时才加上)新增另一个条件;如果所有的条件都不适用,则使用else (可选的)执行最后的内容。
如:
#!/bin/bash
# This program is used to study if then
# 2013/12/30
echo "Press y to continue"
read yn
if [ "$yn" = "y" ] || [ "$yn" = "Y" ]; then
echo "script is running..."
elif [ "$yn" = "" ]; then
echo "You must input parameters "
else
echo "STOP!"
fi
二、case ... esac
case 种类方式(string) in <== 开始阶段,种类方式可分成两种类型, 通常使用 $1 这种直接输入类型
种类方式一)
程序执行段
;; <==种类方式一的结束符号
种类方式二)
程序执行段
;;
*)
echo "Usage: { 种类方式一|种类方式二}" <==列出可以利用的参数值
exit 1
esac <== case结束处
种类方式(string)的格式主要有两种:
· 直接输入:就是以“执行文件 + string ”的方式执行(/etc/rc.d/init.d 里的基本设定方式),string可以直接写成$1(在执行文件后直接加入第一个参数)。
· 交 互 式:就是由屏幕输出可能的项,然后让用户输入,通常必须配合read variable,然后string写成$variable 的格式。
如(交互式):
#!/bin/bash
# program: Using case mode
# 2013/12/30
echo "Press your select one, two, three"
read number
case $number in
one)
echo "your choice is one"
;;
two)
echo "your choice is two"
;;
three)
echo "your choice is three"
;;
*)
echo "Usage {one|two|three}"
exit 1
esac
三、循环语句
1、for (( 条件1; 条件2; 条件3)) ---已经知道运行次数
如:
#!/bin/bash
# Using for and loop
# 2013/12/30
declare -i s # <==变量声明
for (( i=1; i<=100; i=i+1 ))
do
s=s+i
done
echo "The count is ==> $s"
2、for variable in variable1 variable2 .....
如:
#!/bin/bash
# using for...do ....done
# 2013/12/30
LIST="a aa aaa aaaa aaaaa"
for i in $LIST
do
echo $i
done
脚本执行结果如下:
a
aa
aaa
aaaa
aaaaa
3、while [ condition1 ] && { | | } [ condition2 ] ... --先判断条件
如:
#!/bin/bash
# Using while and loop
# 2013/12/30
declare -i i
declare -i s
while [ "$i" != "101" ]
do
s=s+i
i=i+1
done
echo "The count is ==> $s"
4、until [ condition1 ] && { | | } [ condition2 ] ... --先做后判断条件
如:
#!/bin/bash # Using until and loop # 2013/12/30 declare -i i declare -i s until [ "$i" = "101" ] do s=s+i i=i+1 done echo "The count is ==> $s"