(三)Linux Shell編程——Shell常用命令(輸出、判斷、循環、函數、包含)


3. 常用命令

3.1 輸出

3.1.1 echo命令

echo是Shell的一個內部指令,用於在屏幕上打印出指定的字符串。命令格式:

echo arg
name="coding"
echo '$name\"'+" ${name}"     #原樣輸出 $name\"+ coding
echo `date`  #當前日期

3.1.2 printf命令

printf 命令用於格式化輸出, 是echo命令的增強版。它是C語言printf()庫函數的一個有限的變形,並且在語法上有些不同。

printf  format-string  [arguments...]   #format-string 為格式控制字符串,arguments 為參數列表
printf "Hello, Shell\n"    #printf 不像 echo 那樣會自動換行,必須顯式添加換行符(\n)
printf "%d %s\n" 1 "abc"   #輸出 1 abc

3.2 if else語句

if 語句通過關系運算符判斷表達式的真假來決定執行哪個分支。Shell 有三種 if ... else 語句:

  • if ... fi 語句;
  • if ... else ... fi 語句;
  • if ... elif ... else ... fi 語句。

3.2.1 if ... fi語句

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

注意:expression 和方括號([ ])之間必須有空格,否則會有語法錯誤。

3.2.2 if ... else ... fi 語句

if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi
a=10
b=20
if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi

if ... else 語句也可以寫成一行,以命令的方式來運行,像這樣:

if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;

if ... else 語句也經常與 test 命令結合使用,test 命令用於檢查某個條件是否成立,與方括號([ ])類似。

a=10
b=20
if [ ${a} == ${b} ]
#if test $[a] -eq $[b]    #數值類型比較 $[num]

3.2.3 if ... elif ... fi 語句

if ... elif ... fi 語句可以對多個條件進行判斷,語法為:

if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

哪一個 expression 的值為 true,就執行哪個 expression 后面的語句;如果都為 false,那么不執行任何語句。

a=10
b=20
if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi

3.3 test命令

test 命令用於檢查某個條件是否成立,它可以進行數值、字符和文件三個方面的測試。

3.3.1 數值比較

語法:

if test $[num1] -eq $[num2]

3.3.2 字符串比較

語法:

if test str1=str2

 3.3.3 文件比較

語法:

if test -e ./bash

另外,Shell還提供了與( ! )、或( -o )、非( -a )三個邏輯操作符用於將測試條件連接起來,其優先級為:“!”最高,“-a”次之,“-o”最低。

3.4 case ... esac語句

case ... esac 與其他語言中的 switch ... case 語句類似,是一種多分枝選擇結構。

語法:

casein
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac

case工作方式如上所示。取值后面必須為關鍵字 in,每一模式必須以右括號結束。取值可以為變量或常數。匹配發現取值符合某一模式后,其間所有命令開始執行直至 ;;。;; 與其他語言中的 break 類似,意思是跳到整個 case 語句的最后。
取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令后不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行后面的命令。

echo 'Input a number between 1 to 4'
echo 'Your number is:\c'
read aNum
case $aNum in
    1)  echo 'You select 1'
    ;;
    2)  echo 'You select 2'
    ;;
    3)  echo 'You select 3'
    ;;
    4)  echo 'You select 4'
    ;;
    *)  echo 'You do not select a number between 1 to 4'
    ;;
esac

3.5 循環

3.5.1 for循環

語法:

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

列表是一組值(數字、字符串等)組成的序列,每個值通過空格分隔。每循環一次,就將列表中的下一個值賦給變量。
in 列表是可選的,如果不用它,for 循環使用命令行的位置參數。

for loop in 1 2 3 4 5
#for str in 'I love Spring'
do
    echo "The value is: $loop"
    #echo ${str}
done

3.5.2 while循環

while循環用於不斷執行一系列命令,也用於從輸入文件中讀取數據;命令通常為測試條件。

語法:

while command
do
   Statement(s) to be executed if command is true
done
COUNTER=0
while [ $COUNTER -lt 5 ]
do
    COUNTER='expr $COUNTER+1'
    echo $COUNTER
done

3.5.3 util循環

until 循環執行一系列命令直至條件為 true 時停止。until 循環與 while 循環在處理方式上剛好相反。一般while循環優於until循環,但在某些時候,也只是極少數情況下,until 循環更加有用。

語法:

until command
do
   Statement(s) to be executed until command is true
done
a=0
until [ ! $a -lt 10 ]
do
   echo $a     #輸出1~9
   a=`expr $a + 1` 
done

3.5.4 break和continue命令

break命令允許跳出所有循環(終止執行后面的所有循環);continue命令會跳出當前循環。

在嵌套循環中,這兩個命令還有較高級的用法:

break 2  #跳出2層循環
continue 2

3.6 Shell函數

3.6.1 函數定義

函數可以讓我們將一個復雜功能划分成若干模塊,讓程序結構更加清晰,代碼重復利用率更高。像其他編程語言一樣,Shell 也支持函數。Shell 函數必須先定義后使用。

函數的定義語法如下:

[ function ] function_name () {
    list of commands
    [ return value ]
}

函數名前可加上關鍵字 function,也可不加,效果一樣。

函數返回值,可以顯式增加return語句;如果不加,會將最后一條命令運行結果作為返回值。

funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"

結果:

[root@centoszang testShell]# ./myShell.sh 
The function is to get the sum of two numbers...
Input first number: 4
Input another number: 5
The two numbers are 4 and 5 !
The sum of two numbers is 9 !

像刪除變量一樣,刪除函數也可以使用 unset 命令,不過要加上 .f 選項

unset .f funWithReturn

3.6.2 函數參數

在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數...

注意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。

funWithParam(){
    echo "The value of the first parameter is $1 !"
    echo "The value of the second parameter is $2 !"
    echo "The value of the tenth parameter is $10 !"
    echo "The value of the tenth parameter is ${10} !"
    echo "The value of the eleventh parameter is ${11} !"
    echo "The amount of the parameters is $# !"  # 參數個數
    echo "The string of the parameters is $* !"  # 傳遞給函數的所有參數
}
funWithParam 1 2 3 4 5 6 7 8 9 18 77

輸出

[root@centoszang testShell]# ./myShell.sh 
The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 18 !
The value of the eleventh parameter is 77 !
The amount of the parameters is 11 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 18 77 !

3.7 Shell文件包含

像其他語言一樣,Shell 也可以包含外部腳本,將外部腳本的內容合並到當前腳本。

兩種語法:

. filename  
source filename

創建被調用腳本 test.sh

name="Java Web"

使用主文件 myShell.sh來引用該腳本

. ./test.sh
echo ${name}    #輸出Java Web

需要注意的是,被包含腳本(test.sh)不需要有執行權限。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM