Skip to content

Latest commit

 

History

History
227 lines (192 loc) · 3.09 KB

File metadata and controls

227 lines (192 loc) · 3.09 KB

提交控制

if语句

if [[ expression ]]
then
   Statement(s) to be executed if expression is true
fi

有三种 if ... else 语句:

if ... fi 语句
if ... else ... fi 语句
if ... elif ... else ... fi 语句

示例

#!/bin/bash/

a=10
b=20
if [ $a == $b ]
then 
	echo "a is equal to b"
elif [ $a -gt $b ]
then
	echo "a is greater to b"
else
	echo "a is less to b"
fi

if ... else 语句也经常与 test 命令结合使用

#!/bin/bash/

a=10
b=20
if test $a == $b 
then 
	echo "a is equal to b"
else
	echo "a is not equal to b"
fi

分支控制:case语句

case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。 语法示例:

#!/bin/bash/

grade="B"

case $grade in 
	"A") echo "Very Good!";;
	"B") echo "Good!";;
	"C") echo "Come On!";;
	*) 
		echo "You Must Try!"
		echo "Sorry!";;
esac

比较全面的例子:

#!/bin/bash
option="${1}"
case ${option} in
   "-f") FILE="${2}"
      echo "File name is $FILE"
      ;;
   "-d") DIR="${2}"
      echo "Dir name is $DIR"
      ;;
   *) 
      echo "`basename ${0}`:usage: [-f file] | [-d directory]"
      exit 1 # Command to come out of the program with status 1
      ;;
esac

运行

./test.sh -f index.html
File name is index.html

下面结合getopts命令介绍下一个经典的例子:从命令行读取参数。

#!/bin/sh
usage()
{
    echo "Usage: $0 -s [start|stop|reload|restart] -e [online|test]"
    exit 1
}

if [ -z $1 ]; then
    usage
fi

while getopts 's:e:h' OPT; do
    case $OPT in
        s) cmd="$OPTARG";;
        e) env="$OPTARG";;
        h) usage;;
        ?) usage;;
    esac
done

echo $cmd
echo $env

运行示例: sh run.sh -s start -e test

for循环

语法

for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done

示例:

#!/bin/bash/

for value in 1 2 3 4 5
do 
	echo "The value is $value"
done

示例2:遍历文件目录

#!/bin/bash
for FILE in *
do
   echo $FILE
done

示例3: 遍历文件内容: city.txt

beijing
tianjin
shanghai

shell

#!/bin/bash

citys=`cat city.txt`
for city in $citys
do
   echo $city
done

while循环

语法:

while command
do
   Statement(s) to be executed if command is true
done

示例:

#!/bin/bash

c=0;
while [ $c -lt 3 ]
do
	echo "Value c is $c"
	c=`expr $c + 1`
done

跳出循环

使用 break 和 continue 来跳出循环。

break:

#!/bin/bash

i=0
while [ $i -lt 5 ]
do
	i=`expr $i + 1`

	if [ $i == 3 ]
		then
			break
	fi
	echo -e $i
done

continue:
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。

#!/bin/bash

i=0
while [ $i -lt 5 ]
do
	i=`expr $i + 1`

	if [ $i == 3 ]
		then
			continue
	fi
	echo -e $i
	
done