Linux大数据开发基础:第十三节:Shell编程入门(五)

本节主要内容while循环控制结构if条件判断

until循环控制结构

1. while循环控制结构

本节例子来源: 语法格式:

while expressiondone(1)计数器格式

适用于循环次数已知或固定时

root.#!/bin/bashi=1while(($i<5))doecho $ilet i++donerootroot(2)标志符结束while循环root@sparkslave02:~/ShellLearning/Chapter13numwhile [[ $num != 4 ]][ ] num ] num root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x flagWhileLoop.sh root@sparkslave02:~/ShellLearning/Chapter13# ./flagWhileLoop.sh Please input the num (1~~10): 4Yes ,you are right !!

## 2. if条件判断## 参考: shell 脚本中的if条件判断功能十分强大,但使用也异常复杂,其语法格式:

if 条件then Commandelse Command#if条件判断的结束,用反拼表示fi

最常用的判断为:判断字符串、判断数字、判断文件及逻辑判断等

(1)判断字符串[ str1!=str2 ];[ -n str1 ];[ -z str1 ];then fi —-当字符串的长度为0时返回真rootstr1=”hello”str2=[ str1=str2 ]then echo “equal”fi#判断两字符串是否不等if [ str1!=str2 ]then echo “not equal”fi#判断字符串长度是否大于0if [ -n str1 ]then echo “the length of str1 is not zero”fi#判断字符串长度是否等于0if [ -z str1 ]then echo “the length of str1 is not zero, it can’t be executed”firootequalthe length of str1 is not zero(2)判断数字-ne -gt -ge -lt -le int2 –小于等于

使用示例:

rooti=2j=3if [ $i -lt $j ]then echo “i is less than j”fiif [ $j -gt $i ]then echo “j is great than i”firootrooti is less than jj is great than i(3)判断文件

文件判断常用命令如下:

-w -x -f -d -c -b -s -e file–如果文件存在为真

使用示例:

rootroot[ -f if03.sh ]then echo “if03.sh exists!!”fi#判断目录是否存在if [ -d ../Chapter13 ]then echo “directory Chapter13 exists!!”firootif03.sh exists!!directory Chapter13 exists!!(4)逻辑判断

逻辑判断主要有下面三个命令

-o–或3. !–非

使用示例:

root[ -f if04.sh -a -d ../Chapter13 ]then echo “file if04.sh and directory Chapter13 both exists!!!”firootrootfile if04.sh and directory Chapter13 both exists!!!(5)if [] then else fi的用法

前面给出的例子都是if [] then fi的形式,这里再给出if [] then else fi的用法

rooti=7if [ $i -lt 6 ]then echo “i is less than 6″else echo “i is great than or equal 6″firootrooti is great than or equal 6(6)if [] then elif then else fi的用法

多种判断,,看示例代码就能明白:

rootrooti=7if [ $i -le 6 ]then echo “i is less than 6″elif [ $i -eq 7 ]then echo “i equal 7″else echo “i is great than 7″firooti equal 7

## 3. until循环控制结构##

语法格式:

until condition docommand done

使用示例:

rooti=0until [ $i -gt 2 ] do let i+=1 echo “i=$i” donerootrooti=1i=2i=3

世上最累人的事,莫过於虚伪的过日子

Linux大数据开发基础:第十三节:Shell编程入门(五)

相关文章:

你感兴趣的文章:

标签云: