1. 程式人生 > >shell編程(二)

shell編程(二)

basename xitong ipp 嵌套循環 htm doc 描述 標準輸出 開始

Shell echo命令

echo是Shell的一個內部指令,用於在屏幕上打印出指定的字符串。可以使用echo實現更復雜的輸出格式控制。

顯示轉義字符

echo "\"It is a test\""

結果是:
"It is a test"

顯示變量

name="OK"
echo "$name It is a test"

結果是:
OK It is a test

如果變量與其它字符相連的話,需要使用大括號({ }):

mouth=8
echo "${mouth}-1-2009"

結果將是: 8-1-2009

顯示換行

echo "OK!\n"
echo "It is a test"

輸出: OK! It is a test

顯示不換行

echo "OK!\c"
echo "It is a test"、

輸出: OK!It si a test

顯示結果重定向至文件

echo "It is a test" > myfile

原樣輸出字符串

若需要原樣輸出字符串(不進行轉義),請使用單引號。例如:

echo $name\"

顯示命令執行結果

echo `date`

結果顯示當前日期

shell printf命令:格式化輸出語句

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

註意:printf 由 POSIX 標準所定義,移植性要比 echo 好。如同 echo 命令,printf 命令也可以輸出簡單的字符串:

$printf "Hello, Shell\n"
Hello, Shell
$

printf 不像 echo 那樣會自動換行,必須顯式添加換行符(\n)。

printf 命令的語法:

  printf format-string [arguments...]

format-string 為格式控制字符串,arguments 為參數列表。

printf()在C語言入門教程中已經講到,功能和用法與 printf 命令類似,請查看:C語言格式輸出函數printf()詳解

這裏僅說明與C語言printf()函數的不同:

  • printf 命令不用加括號
  • format-string 可以沒有引號,但最好加上,單引號雙引號均可。
  • 參數多於格式控制符(%)時,format-string 可以重用,可以將所有參數都轉換。
  • arguments 使用空格分隔,不用逗號。
# format-string為雙引號
$ printf "%d %s\n" 1 "abc"
1 abc
# 單引號與雙引號效果一樣 
$ printf %d %s\n 1 "abc" 
1 abc
# 沒有引號也可以輸出
$ printf %s abcdef
abcdef
# 格式只指定了一個參數,但多出的參數仍然會按照該格式輸出,format-string 被重用
$ printf %s abc def
abcdef
$ printf "%s\n" abc def
abc
def
$ printf "%s %s %s\n" a b c d e f g h i j
a b c
d e f
g h i
j
# 如果沒有 arguments,那麽 %s 用NULL代替,%d 用 0 代替
$ printf "%s and %d \n" 
and 0
# 如果以 %d 的格式來顯示字符串,那麽會有警告,提示無效的數字,此時默認置為 0
$ printf "The first program always prints‘%s,%d\n‘" Hello Shell
-bash: printf: Shell: invalid number
The first program always prints ‘Hello,0
$

Shell if else語句

可以類比C語言,與C語言的不同之處在於有fi結尾,以及每個if後邊都有一個then

  • if ... fi 語句;
  • if ... else ... fi 語句;
  • if ... elif ... else ... fi 語句
if [ expression ]:註意:expression 和方括號([ ])之間必須有空格,否則會有語法錯誤。

#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi


結果:a is not equal to b
#!/bin/sh
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

運行結果:
a is less than b

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

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

if ... else 語句也經常與 test 命令結合使用,如下所示:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]   #test 命令用於檢查某個條件是否成立,與方括號([ ])類似。
then
    echo The two numbers are equal!
else
    echo The two numbers are not equal!
fi

輸出:
The two numbers are equal!

Shell test命令

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

數值測試

參數說明
-eq 等於則為真
-ne 不等於則為真
-gt 大於則為真
-ge 大於等於則為真
-lt 小於則為真
-le 小於等於則為真
    num1=100
    num2=100
    if test $[num1] -eq $[num2]
    then
        echo The two numbers are equal!
    else
        echo The two numbers are not equal!
    fi
  
  輸出:The two numbers are equal

字符串測試

參數說明
= 等於則為真
!= 不相等則為真
-z 字符串 字符串長度偽則為真
-n 字符串 字符串長度不偽則為真
    num1=100
    num2=100
    if test num1=num2
    then
        echo The two strings are equal!
    else
        echo The two strings are not equal!
    fi

  輸出:The two strings are equal

文件測試

參數說明
-e 文件名 如果文件存在則為真
-r 文件名 如果文件存在且可讀則為真
-w 文件名 如果文件存在且可寫則為真
-x 文件名 如果文件存在且可執行則為真
-s 文件名 如果文件存在且至少有一個字符則為真
-d 文件名 如果文件存在且為目錄則為真
-f 文件名 如果文件存在且為普通文件則為真
-c 文件名 如果文件存在且為字符型特殊文件則為真
-b 文件名 如果文件存在且為塊特殊文件則為真
    cd /bin
    if test -e ./bash
    then
        echo The file already exists!
    else
        echo The file does not exists!
    fi
  
  輸出:The file already exists

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

cd /bin
if test -e ./notFile -o ./bash
then
    echo One file exists at least!
else
    echo Both dose not exists!
fi

輸出:One file exists at least

Shell case esac語句

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

case 語句匹配一個值或一個模式,如果匹配成功,執行相匹配的命令。case語句格式如下:

case 值 in
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac

case工作方式如上所示。取值後面必須為關鍵字 in,每一模式必須以右括號結束。取值可以為變量或常數。匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;。;; 與其他語言中的 break 類似,意思是跳到整個 case 語句的最後。

取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令後不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。

下面的腳本提示輸入1到4,與每一種模式進行匹配:

    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

  輸入不同的內容,會有不同的結果,例如:
  Input a number between 1 to 4
  Your number is:3
  You select 3
    #!/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
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$

Shell for循環

for循環一般格式為:

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

列表是一組值(數字、字符串等)組成的序列,每個值通過空格分隔。每循環一次,就將列表中的下一個值賦給變量。

in 列表是可選的,如果不用它,for 循環使用命令行的位置參數。

    #順序輸出當前列表中的數字: 
    for loop in 1 2 3 4 5
    do
        echo "The value is: $loop"
    done

    結果:
    The value is: 1
    The value is: 2
    The value is: 3
    The value is: 4
    The value is: 5

    #順序輸出字符串中的字符: 
    for str in This is a string
    do
        echo $str
    done
    
    結果:This is a string


    #顯示主目錄下以 .bash 開頭的文件: 
    #!/bin/bash
    for FILE in $HOME/.bash*
    do
       echo $FILE
    done
        
    結果
    /root/.bash_history
    /root/.bash_logout
    /root/.bash_profile
    /root/.bashrc

Shell while循環

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

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

命令執行完畢,控制返回循環頂部,從頭開始直至測試條件為假。

以下是一個基本的while循環,測試條件是:如果COUNTER小於5,那麽返回 true。COUNTER從0開始,每次循環處理時,COUNTER加1。運行上述腳本,返回數字1到5,然後終止。

    COUNTER=0
    while [ $COUNTER -lt 5 ]
    do
        COUNTER=expr $COUNTER+1
        echo $COUNTER
    done
  
  結果:
  1   2   3   4   5

#while循環可用於讀取鍵盤信息。下面的例子中,輸入信息被設置為變量FILM,按<Ctrl-D>結束循環。 

    echo type <CTRL-D> to terminate
    echo -n enter your most liked film: 
    while read FILM
    do
        echo "Yeah! great film the $FILM"
    done

    運行腳本,輸出類似下面:
    type <CTRL-D> to terminate
    enter your most liked film: Sound of Music
    Yeah! great film the Sound of Music

Shell until循環

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

until 循環格式為:

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

command 一般為條件表達式,如果返回值為 false,則繼續執行循環體內的語句,否則跳出循環。

例如,使用 until 命令輸出 0 ~ 9 的數字:
#!/bin/bash
a=0
until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done 

運行結果:
0
1
2
3
4
5
6
7
8
9

Shell break和continue命令

在循環過程中,有時候需要在未達到循環結束條件時強制跳出循環,像大多數編程語言一樣,Shell也使用 break 和 continue 來跳出循環。

break命令

break命令允許跳出所有循環(終止執行後面的所有循環)。

下面的例子中,腳本進入死循環直至用戶輸入數字大於5。要跳出這個循環,返回到shell提示符下,就要使用break命令。

    #!/bin/bash
    while :
    do
        echo -n "Input a number between 1 to 5: "
        read aNum
        case $aNum in
            1|2|3|4|5) echo "Your number is $aNum!"
            ;;
            *) echo "You do not select a number between 1 to 5, game is over!"
                break
            ;;
        esac
    done

在嵌套循環中,break 命令後面還可以跟一個整數,表示跳出第幾層循環。例如:

break n    #表示跳出第 n 層循環。

下面是一個嵌套循環的例子,如果 var1 等於 2,並且 var2 等於 0,就跳出循環:

    #!/bin/bash
    for var1 in 1 2 3
    do
       for var2 in 0 5
       do
          if [ $var1 -eq 2 -a $var2 -eq 0 ]
          then
             break 2
          else
             echo "$var1 $var2"
          fi
       done
    done

    結果:
    如上,break 2 表示直接跳出外層循環。運行結果:
    1 0
    1 5

continue命令

continue命令與break命令類似,只有一點差別,它不會跳出所有循環,僅僅跳出當前循環。

對上面的例子進行修改:

    #!/bin/bash
    while :
    do
        echo -n "Input a number between 1 to 5: "
        read aNum
        case $aNum in
            1|2|3|4|5) echo "Your number is $aNum!"
            ;;
            *) echo "You do not select a number between 1 to 5!"
                continue
                echo "Game is over!"
            ;;
        esac
    done

    結果:
    運行代碼發現,當輸入大於5的數字時,該例中的循環不會結束,語句
    echo "Game is over!"
    永遠不會被執行。

同樣,continue 後面也可以跟一個數字,表示跳出第幾層循環。

再看一個 continue 的例子:

    #!/bin/bash
    NUMS="1 2 3 4 5 6 7"
    for NUM in $NUMS
    do
       Q=`expr $NUM % 2`
       if [ $Q -eq 0 ]
       then
          echo "Number is an even number!!"
          continue
       fi
       echo "Found odd number"
    done

    運行結果:
    Found odd number
    Number is an even number!!
    Found odd number
    Number is an even number!!
    Found odd number
    Number is an even number!!
    Found odd numbe

Shell函數:Shell函數返回值、刪除函數、在終端調用函數

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

Shell 函數的定義格式如下:

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

如果你願意,也可以在函數名前加上關鍵字 function:

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

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

Shell 函數返回值只能是整數,一般用來表示函數執行成功與否,0表示成功,其他值表示失敗。如果 return 其他數據,比如一個字符串,往往會得到錯誤提示:“numeric argument required”。

如果一定要讓函數返回字符串,那麽可以先定義一個變量,用來接收函數的計算結果,腳本在需要的時候訪問這個變量來獲得函數返回值。

先來看一個例子:

    #!/bin/bash
    # Define your function here
    Hello () {
       echo "Url is http://see.xidian.edu.cn/cpp/shell/"
    }
    # Invoke your function
    Hello
  
  運行結果:
  $./test.sh   Hello World   $

調用函數只需要給出函數名,不需要加括號。

再來看一個帶有return語句的函數:

    #!/bin/bash
    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 !"

    運行結果:
    The function is to get the sum of two numbers...
    Input first number: 25
    Input another number: 50
    The two numbers are 25 and 50 !
    The sum of two numbers is 75 !

函數返回值在調用該函數後通過 $? 來獲得。

再來看一個函數嵌套的例子:

    #!/bin/bash
    # Calling one function from another
    number_one () {
       echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
       number_two
    }
    number_two () {
       echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
    }
    number_one

    運行結果:
    Url_1 is http://see.xidian.edu.cn/cpp/shell/
    Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/

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

$unset .f function_name

如果你希望直接從終端調用函數,可以將函數定義在主目錄下的 .profile 文件,這樣每次登錄後,在命令提示符後面輸入函數名字就可以立即調用。

Shell函數參數

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

帶參數的函數示例:

    #!/bin/bash
    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 34 73

    運行腳本:
    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 34 !
    The value of the eleventh parameter is 73 !
    The amount of the parameters is 12 !
    The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"

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

另外,還有幾個特殊變量用來處理參數,前面已經提到:

特殊變量 說明
$# 傳遞給函數的參數個數。
$* 顯示所有傳遞給函數的參數。
$@ 與$*相同,但是略有區別,請查看Shell特殊變量。
$? 函數的返回值。

Shell輸入輸出重定向:Shell Here Document,/dev/null文件

Unix 命令默認從標準輸入設備(stdin)獲取輸入,將結果輸出到標準輸出設備(stdout)顯示。一般情況下,標準輸入設備就是鍵盤,標準輸出設備就是終端,即顯示器。

輸出重定向

命令的輸出不僅可以是顯示器,還可以很容易的轉移向到文件,這被稱為輸出重定向。

命令輸出重定向的語法為:

  $ command > file

這樣,輸出到顯示器的內容就可以被重定向到文件。

例如,下面的命令在顯示器上不會看到任何輸出:

$ who > users

打開 users 文件,可以看到下面的內容:

$ cat users
oko         tty01   Sep 12 07:30
ai          tty15   Sep 12 13:32
ruth        tty21   Sep 12 10:10
pat         tty24   Sep 12 13:07
steve       tty25   Sep 12 13:03
$

輸出重定向會覆蓋文件內容,請看下面的例子:

$ echo line 1 > users
$ cat users
line 1
$

如果不希望文件內容被覆蓋,可以使用 >> 追加到文件末尾,例如:

$ echo line 2 >> users
$ cat users
line 1
line 2
$

輸入重定向

和輸出重定向一樣,Unix 命令也可以從文件獲取輸入,語法為:

command < file

這樣,本來需要從鍵盤獲取輸入的命令會轉移到文件讀取內容。

註意:輸出重定向是大於號(>),輸入重定向是小於號(<)。

例如,計算 users 文件中的行數,可以使用下面的命令:

$ wc -l users
2 users
$

也可以將輸入重定向到 users 文件:

$ wc -l < users
2
$

註意:上面兩個例子的結果不同:第一個例子,會輸出文件名;第二個不會,因為它僅僅知道從標準輸入讀取內容。

重定向深入講解

一般情況下,每個 Unix/Linux 命令運行時都會打開三個文件:

  • 標準輸入文件(stdin):stdin的文件描述符為0,Unix程序默認從stdin讀取數據。
  • 標準輸出文件(stdout):stdout 的文件描述符為1,Unix程序默認向stdout輸出數據。
  • 標準錯誤文件(stderr):stderr的文件描述符為2,Unix程序會向stderr流中寫入錯誤信息。


默認情況下,command > file 將 stdout 重定向到 file,command < file 將stdin 重定向到 file。

如果希望 stderr 重定向到 file,可以這樣寫:

  1. $command 2 > file

如果希望 stderr 追加到 file 文件末尾,可以這樣寫:

  1. $command 2 >> file

2 表示標準錯誤文件(stderr)。

如果希望將 stdout 和 stderr 合並後重定向到 file,可以這樣寫:

$command > file 2>&1
或
$command >> file 2>&1

如果希望對 stdin 和 stdout 都重定向,可以這樣寫:

$command < file1 >file2

command 命令將 stdin 重定向到 file1,將 stdout 重定向到 file2。

命令 說明
command > file 將輸出重定向到 file。
command < file 將輸入重定向到 file。
command >> file 將輸出以追加的方式重定向到 file。
n > file 將文件描述符為 n 的文件重定向到 file。
n >> file 將文件描述符為 n 的文件以追加的方式重定向到 file。
n >& m 將輸出文件 m 和 n 合並。
n <& m 將輸入文件 m 和 n 合並。
<< tag 將開始標記 tag 和結束標記 tag 之間的內容作為輸入。

Here Document

Here Document 目前沒有統一的翻譯,這裏暫譯為”嵌入文檔“。Here Document 是 Shell 中的一種特殊的重定向方式,它的基本的形式如下:

command << delimiter
    document
delimiter

它的作用是將兩個 delimiter 之間的內容(document) 作為輸入傳遞給 command。

註意:

  • 結尾的delimiter 一定要頂格寫,前面不能有任何字符,後面也不能有任何字符,包括空格和 tab 縮進。
  • 開始的delimiter前後的空格會被忽略掉。

下面的例子,通過 wc -l 命令計算 document 的行數:

$wc -l << EOF
    This is a simple lookup program
    for good (and bad) restaurants
    in Cape Town.
EOF
3
$

也可以 將 Here Document 用在腳本中,例如:

#!/bin/bash
cat << EOF
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
EOF

 運行結果

This is a simple lookup program
for good (and bad) restaurants
in Cape Town.

下面的腳本通過 vi 編輯器將 document 保存到 test.txt 文件:

#!/bin/sh
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands

運行腳本:

$ sh test.sh
Vim: Warning: Input is not from a terminal
$

打開 test.txt,可以看到下面的內容:

$ cat test.txt
This file was created automatically from
a shell script
$

/dev/null 文件

如果希望執行某個命令,但又不希望在屏幕上顯示輸出結果,那麽可以將輸出重定向到 /dev/null:

  1. $ command > /dev/null

/dev/null 是一個特殊的文件,寫入到它的內容都會被丟棄;如果嘗試從該文件讀取內容,那麽什麽也讀不到。但是 /dev/null 文件非常有用,將命令的輸出重定向到它,會起到”禁止輸出“的效果。

如果希望屏蔽 stdout 和 stderr,可以這樣寫:

$ command > /dev/null 2>&1

Shell文件包含

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

Shell 中包含腳本可以使用:

  1. . filename

  1. source filename

兩種方式的效果相同,簡單起見,一般使用點號(.),但是註意點號(.)和文件名中間有一空格。

例如,創建兩個腳本,一個是被調用腳本 subscript.sh,內容如下:

url="http://see.xidian.edu.cn/cpp/view/2738.html"

一個是主文件 main.sh,內容如下:

#!/bin/bash
. ./subscript.sh
echo $url

執行腳本:

$chomd +x main.sh
./main.sh
http://see.xidian.edu.cn/cpp/view/2738.html
$

註意:被包含腳本不需要有執行權限。

shell編程(二)