Linux-shell脚本编程-结构化命令

if-then语句:
if command 
	then commands
fi
该语句首先执行if后的命令,如果该命令的退出状态码是0,则then后的语句执行。

例子:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
echo "this is my first command"
echo "this is my second command"
echo "dafhfhjdshkjahsjjkf"
ls -a /home/$user
fi

if-then-else 语句 :
if command 
then    
	commands
else   
	commands 
fi 

例子:
#!/bin/bash 
user=hgy

if grep $user /etc/passwd 
then
	 echo "The bash files for user $user are:"  
	ls -a /home/$user
	echo 
else    
	 echo "The user $testuser does not exist on this system."    
	 echo
fi 
 
嵌套if

例子:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
	echo "the user $user exists on this system"
else
	echo "the user $user does not exist on this system"
	if ls -d /home/$user/
	then
		echo "however $user has a diretory"
	fi
fi


------------------------------------------------------------------------------------------
if command1
 then 
 	   commands 
elif command2 
then    
       more commands 
fi

上述例子可以改写为:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
	echo "the user $user exists on this system"
elif  ls -d /home/$user/
then
	echo "the user $user does not exist on this system"
	echo "however $user has a diretory"
fi

test命令提供了在if-then语句中测试不同条件的途径。如果test命令中列出的条件成立, test命令就会退出并返回退出状态码0。这样if-then语句就与其他编程语言中的if-then语句 以类似的方式工作了。如果条件不成立,test命令就会退出并返回非零的退出状态码,这使得 if-then语句不会再被执行。

if test condition
then
	commands
fi
也可以使用如下形式代替:
if  [ condition ]
then
	commands
fi

数值比较:
eq --等于			ge --大于等于			gt --大于		le --小于等于		lt --小于		ne --不等于

字符串比较:
=			!=				<			>  			-n  str   --str的长度是否非0		-z str  --str的长度是否为0

case命令:
case variable in 
	pattern1 | pattern2) commands1;; 
	pattern3) commands2;;
	 *) default commands;; 
esac 
for命令:
for var in list
do
	commands
done
c语言风格的for语句:
for (( variable assignment ; condition ; iteration process )) 

如 for( (a=1; a<10; a++))
while语句
while test command
do
	commands
done

例子:
#!/bin/bash
var1=10
while [ $var1 -gt 0 ]
do
	echo $var1
	var1=$[ var1 - 1 ]
done
until命令:
	until命令要求你指定一个通常返回非零退 出状态码的测试命令。只有测试命令的退出状态码不为0,
bash shell才会执行循环中列出的命令。 一旦测试命令返回了退出状态码0,循环就结束了。 

until test command 	
do
	commands
done

例子:
#!/bin/bash 
var=100
until [ $var -eq 0 ]
do
	echo $var
	var=$[ $var - 10 ]
done
linux-shell中同样可以使用break和continue来控制循环

break用来跳出当前循环,继续往下执行。
continue用来跳出循环,继续下一次循环。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值