歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux shell入門之流程控制語句

Linux shell入門之流程控制語句

日期:2017/3/1 9:26:21   编辑:SHELL編程

1.case


腳本:

#!/bin/bash
#a test about case
case $1 in
   "lenve")  echo "input lenve";;
   "hello")  echo "input hello";;
   [a-zA-Z]) echo "It's a letter";;
   [0-9]) echo "It's a number";;
esac

執行效果:


2.while


腳本(注意=兩端不能有空格):

#!/bin/bash
#a test about while
a=1
while [ $a -lt 10 ]
do
  echo "hello world!${a}"
  a=`expr $a + 1`
done

輸出:


3.until循環類似於while循環,不同的是until是判斷條件為false時才會執行


#!/bin/bash
#a test about until
a=11
until [ $a -lt 10 ]
do
  echo "hello world!${a}"
  a=`expr $a + 1`
done

這是一個無限死循環,輸出從hello world11到hello world無窮大。


4.break與continue


continue腳本

#!/bin/bash
#a test about continue
a=1
while [ $a -lt 10 ]
do
  if [ $a -eq 5 ]
  then
   a=`expr $a + 1`
   continue
  else
  echo "hello world!${a}"
  fi
  a=`expr $a + 1`
done

結果:

break腳本:

#!/bin/bash
#a test about break
a=1
while [ $a -lt 10 ]
do
  if [ $a -eq 5 ]
  then
   a=`expr $a + 1`
   break
  else
  echo "hello world!${a}"
  fi
  a=`expr $a + 1`
done

運行結果:


5.shift指令,參數左移,每執行一次,參數序列順次左移一個位置,$#的位置減1。此指令可用來分別處理每個參數,移出去的參數不可再用。


一個求和的例子:

#!/bin/bash
#a test about shift
if [ $# -le 0 ]
then
echo "there is no parameters"
exit 0
fi
sum=0
while [ $# -gt 0 ]
do
  sum=`expr $sum + $1`
  shift
done
echo $sum

千萬注意=兩端不能有空格
運行結果:

Linux Shell在while中用read從鍵盤輸入 http://www.linuxidc.com/Linux/2015-06/118831.htm

Linux Shell 程序調試 http://www.linuxidc.com/Linux/2015-07/119880.htm

Linux Shell腳本面試25問 http://www.linuxidc.com/Linux/2015-04/116474.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、轉義字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved