if,for,while

1.shell流程控制

流程控制是改变程序运行顺序的指令。linux shell有一套自己的流程控制语句,其中包括条件语句(if),循环语句(for,while),选择语句(case)。下面我将通过例子介绍下,各个语句使用方法

read -p

黑洞文件:/dev/null

2.if语句,条件判断,真假

格式:

格式:if list; then list; [ elif list; then list; ] ... [ else list; ] fi

2.1单分支

if 条件表达式; then

命令

fi

实例:

#!/bin/bash

N=10

if [ $N -gt 5 ]; then

  echo yes

fi

# bash test.sh

yes

2.2双分支

if 条件表达式; then

  命令

else

  命令

fi

实例1:

#!/bin/bash

N=10

if [ $N -lt 5 ]; then

  echo yes

else

  echo no

fi

#bash -x test.sh #-x测试

# bash test.sh

no

实例2:判断crond进程是否在运行

#!/bin/bash

NAME=crond

NUM=$(ps aux | grep $NAME | grep -vc "grep")

if [ $NUM -eq 1 ]; then

  echo "$NAME running."

else

  echo "$NAME is not running!"

fi

实例3

#!/bin/bash

if ping -c 1 192.168.1.1 &>/dev/null; then #将ping的结果写入到黑洞文件中

  echo "OK."

else

  echo "NO!"

fi

2.3多分支

if 条件表达式; then

  命令

elif 条件表达式; then

  命令

else

  命令

fi

实例

#!/bin/bash

N=$1

if [ $N -eq 3 ]; then

  echo "eq 3"

elif [ $N -eq 5 ]; then

  echo "eq 5"

elif [ $N -eq 8 ]; then

  echo "eq 8"

else

  echo "no"

fi

3.shell编程之if语句实战案例

需求:

1. 完成用户输入文件或者目录的自动复制,并可以实现用户指定复制目标位置。

2. 用户体验佳。

#!/bin/bash

read -p "pls enter a file you want to copy:" file

if [ -f $file -o -d $file ];then

read -p "do you want to copy the $file?(y/n)" sure

     confirm=$(echo ${sure} | tr A-Z a-z)

if [ "$confirm" == "y" ];then

read -p "where do you want to copy?" dire

if [ -d $dire ];then

cp -a $file $dire

echo "the $file copied to $dire"

else

echo "the $dire is not exists"

exit 1

fi

elif [ "$confirm" == "n" ];then

echo "bye"

else

echo "pls input y or n"

fi

else

echo "the $file is not exists"

fi

4.for语句,批量化

格式:for name [ [ in [ word ... ] ] ; ] do list ; done

for 变量名 in 取值列表

do

  命令

done

实例1:

#!/bin/bash

for i in {1..3}; do

  echo $i

done

# bash test.sh

2

实例2:计算100以内偶数和

#!/bin/bash

sum=0

for i in `seq 2 2 100`

do

let sum+=$i

done

echo "$sum"

5.shell编程之for语句实战案例

1. 批量检查当前教室主机是否在线

#!/bin/bash

. /etc/init.d/functions #加载库

ip=192.168.88.

for i in {1..20}

do

if ping -c 1 -w 1 $ip$i &>/dev/null;then

echo -n "$ip$i在线!" #-n是换行的意思

success

echo ""

else

echo -n "$ip$i不在线!"

failure

echo ""

fi

done

6.while语句,后台检测

条件为真就进入死循环;条件为假就退出循环

格式:while list; do list; done

while 条件表达式; do

命令

done

7.break和continue语句只能用在while和for中

break 是终止循环。

continue 是跳出当前循环。

8.case语句

case 语句一般用于选择性来执行对应部分块命令。

case 模式名 in

模式 1)

  命令

  ;;

模式 2)

  命令

  ;;

*)

  不符合以上模式执行的命令

esac

每个模式必须以右括号结束,命令结尾以双分号结束,最后一个模式不需要添加;;。

9.shell编程高级实战

bash test_tty.sh & : 关掉终端脚本停止运行,&代表后台运行,会生成一个tty文件,查看这个文件可以知道运行状态

nohup bash test_tty.sh &: 关掉终端脚本不停止运行,关掉脚本用kill。

猜你喜欢

转载自www.cnblogs.com/liangzb310/p/11026414.html