shell腳本編程之處理用戶輸入

技術交流QQ群:1027579432,歡迎你的加入!

歡迎關注我的微信公眾號:CurryCoder的程序人生

本教程使用Linux發(fā)行版Centos7.0系統(tǒng),請您注意~

1.命令行參數(shù)

  • bash shell提供了一些不同的方法來從用戶處獲得數(shù)據(jù),包括命令行參數(shù)(添加在命令后的數(shù)據(jù))、命令行選項(可修改命令行為的單個字母)以及直接從鍵盤讀取輸入的能力。
  • 向shell腳本傳遞數(shù)據(jù)的最基本方法是使用命令行參數(shù),命令行參數(shù)允許你在運行腳本時向命令行添加數(shù)據(jù)。例如 ./addem 10 30
1.1 讀取參數(shù)
  • bash shell會將一些稱為位置參數(shù)的特殊變量分配給輸入到命令行中的所有參數(shù),這也包括腳本的名稱。位置參數(shù)變量是標準的數(shù)字:$0是程序名,$1是第一個參數(shù),$2是第二個參數(shù),以此類推,$9是第九個參數(shù)。如下例所示:
    #!/bin/bash
    
    
    var=1
    for (( n = 1; n <= $1; n++ ))
    do
        var=$[ $var * n ]
    done
    
    echo "The var of $1 is $var"
    
    # 結果
    [njust@njust tutorials]$ ./bar1.sh 5  # 注意命令行中的參數(shù)5
    The var of 5 is 120
    
  • 可以在shell腳本中像使用普通變量一樣使用$1變量,shell腳本會自動將命令行參數(shù)的值分配給變量,不需要你作任何處理。如果需要輸入更多的命令行參數(shù),則每個參數(shù)之間都必須用空格分開。如下例所示:
    #!/bin/bash
    
    res=$[ $1 * $2 ]
    
    echo "The first parameter is $1"
    echo "The second parameter is $2"
    echo "The final result is $res"
    
    # 結果
    [njust@njust tutorials]$ ./bar2.sh 3 5  # 輸入更多命令行參數(shù)時,參數(shù)之間用空格進行分割!
    The first parameter is 3
    The second parameter is 5
    The final result is 15
    
  • 在上面的例子中,用到的命令行參數(shù)都是數(shù)值,也可以在命令行上使用文本字符串。如下例所示:
    #!/bin/bash
    
    echo "Hello $1, glad to meet you."
    
    # 結果
    [njust@njust tutorials]$ ./bar3.sh Curry
    Hello Curry, glad to meet you.
    
  • shell將輸入到命令行的字符串值傳遞給腳本,但碰到含有空格的文本字符串時就會出現(xiàn)問題,因為每個命令行參數(shù)都是用空格分隔的,所以shell會將空格當成兩個值的分隔符。解決方法:對含有空格的文本字符串,必須要用引號。如下例所示:
    [njust@njust tutorials]$ ./bar3.sh 'James Harden'
    Hello James Harden, glad to meet you.
    
  • 當命令行參數(shù)不只9個時,在第九個變量后,必須在變量數(shù)字周圍加上花括號{},例如${10},如下例所示:
    #!/bin/bash
    
    
    res=$[ ${10} * ${11} ]
    
    echo "The tenth parameter is ${10}"
    echo "The eleventh parameter is ${11}"
    
    echo "The final result is $res"
    
    # 結果
    [njust@njust tutorials]$ ./bar4.sh 1 2 3 4 5 6 7 8 9 10 11
    The tenth parameter is 10
    The eleventh parameter is 11
    The final result is 110
    
1.2 讀取腳本名
  • 可以使用$0參數(shù)獲取shell在命令行啟動的腳本名稱,如下例所示:
    #!/bin/bash
    
    echo "The zero parameter is set to: $0"
    
    # 結果
    [njust@njust tutorials]$ bash bar5.sh   # 注意此處運行腳本的格式?。。?The zero parameter is set to: bar5.sh
    
  • 問題一:如果使用./bar5.sh方式運行腳本,命令會和腳本混在一起,出現(xiàn)在$0參數(shù)中。如下例所示:
    [njust@njust tutorials]$ ./bar5.sh 
    The zero parameter is set to: ./bar5.sh
    
  • 問題二:當傳給$0變量的實際字符串不僅僅是腳本名,而是完整的腳本路徑時,變量$0就會使用整個路徑。如下例所示:
    [njust@njust tutorials]$ bash /home/njust/tutorials/bar5.sh
    The zero parameter is set to: /home/njust/tutorials/bar5.sh
    
  • 解決方法:為了把腳本的運行路徑給剝離掉,同時,還要刪除與腳本名混雜在一起的命令,可以使用basename命令會返回不包含路徑的腳本名。如下例所示:
    #!/bin/bash
    
    name=$(basename $0)
    
    
    echo
    echo "The script name is:$name"
    
    # 結果
    [njust@njust tutorials]$ ./bar6.sh 
    
    The script name is:bar6.sh
    # 結果
    [njust@njust tutorials]$ bash bar6.sh 
    
    The script name is:bar6.sh
    
  • 可以使用上述方法來編寫基于腳本名執(zhí)行不同功能的腳本。如下例所示:
    #!/bin/bash
    
    name=$(basename $0)
    
    if [ $name = "addem" ]
    then
        res=$[ $1 + $2 ]
    elif [ $name = "multem" ]
    then    
        res=$[ $1 * $2 ]
    fi
    echo "The calculated value is:$res"
    
    # 通過復制文件創(chuàng)建addem
    [njust@njust tutorials]$ cp bar7.sh addem
    [njust@njust tutorials]$ chmod u+x bar7.sh 
    
    # 通過軟鏈接創(chuàng)建multem
    [njust@njust tutorials]$ ln -s bar7.sh  multem
    
    # 查看創(chuàng)建的文件
    [njust@njust tutorials]$ ls -l *em
    -rwxrw-r--. 1 njust njust 180 4月   2 21:01 addem
    lrwxrwxrwx. 1 njust njust   7 4月   2 21:02 multem -> bar7.sh
    
    # 最終結果
    [njust@njust tutorials]$ ./addem 2 8
    The calculated value is:10
    [njust@njust tutorials]$ ./multem 2 8
    The calculated value is:16
    
1.3 測試參數(shù)
  • 在shell腳本中使用命令行參數(shù)時要小心,如果不加參數(shù)運行,可能會出現(xiàn)問題。如下例所示:
    [njust@njust tutorials]$ ./addem 4
    ./addem:行7: 4 +  : 語法錯誤: 期待操作數(shù) (錯誤符號是 "+  ")
    The calculated value is:
    
  • 當腳本認為參數(shù)變量中會有數(shù)據(jù)而實際上并沒有時,腳本很可能會產(chǎn)生錯誤消息。這樣的腳本寫法并不好,在使用參數(shù)前一定要檢查其中是否存在數(shù)據(jù)。如下例所示:
    #!/bin/bash
    
    if [ -n "$1" ]  # -n測試來檢查命令行參數(shù)$1中是否有數(shù)據(jù)
    then
        echo "Hello $1,glad to meet you."
    else
        echo "Sorry,you did not identify yourself."
    fi
    
    # 結果
    [njust@njust tutorials]$ ./bar8.sh Curry
    Hello Curry,glad to meet you.
    
    [njust@njust tutorials]$ ./bar8.sh
    Sorry,you did not identify yourself.
    

2.特殊參數(shù)變量

  • 在bash shell中有些特殊變量,它們會記錄命令行參數(shù)。具體如下介紹:
2.1 參數(shù)統(tǒng)計
  • 在腳本中使用命令行參數(shù)之前應該檢查一下命令行參數(shù),可以統(tǒng)計一下命令行中輸入了多少個參數(shù),無需測試每個參數(shù)。bash shell提供了特殊變量$#,它含有腳本運行時攜帶的命令行參數(shù)的個數(shù),可以在腳本中任何地方使用這個特殊變量,與普通變量一樣。如下例所示:
    #!/bin/bash
    
    echo "There were $# parameters supplied."
    
    # 結果
    [njust@njust tutorials]$ ./bar9.sh 
    There were 0 parameters supplied.
    
    [njust@njust tutorials]$ ./bar9.sh 1 2 3
    There were 3 parameters supplied.
    
  • 在使用參數(shù)前測試參數(shù)的總和,如下例所示:
    #!/bin/bash
    
    if [ $# -ne 2 ]  # -ne測試命令行參數(shù)數(shù)量,如果參數(shù)數(shù)量不對,就會顯示一條錯誤消息告知腳本的正確用法。
    then
        echo "Usage: bar10.sh a b"
    else
        res=$[ $1 + $2 ]
        echo "result is $res"
    fi
    
    # 結果
    [njust@njust tutorials]$ ./bar10.sh 
    Usage: bar10.sh a b
    
    [njust@njust tutorials]$ ./bar10.sh 2 
    Usage: bar10.sh a b
    
    [njust@njust tutorials]$ ./bar10.sh 2 3
    result is 5
    
  • $#變量含有參數(shù)的總和,因此變量${!#}就代表了命令行中最后一個參數(shù)。注意:當命令行上沒有任何參數(shù)時,$#的值為0,params變量的值也一樣,但${!#}變量會返回命令行的腳本名,如下例所示:
    #!/bin/bash
    
    params=$#
    
    echo "The last parameter is $params."
    echo "The last parameter is ${!#}"
    
    # 結果
    [njust@njust tutorials]$ ./bar11.sh 12 3 42 
    The last parameter is 3.
    The last parameter is 42
    
    [njust@njust tutorials]$ ./bar11.sh 
    The last parameter is 0.
    The last parameter is ./bar11.sh
    
2.2 抓取所有的數(shù)據(jù)
  • 有時候需要抓取命令行上所有的參數(shù),此時不需要先用$#變量來判斷命令行上總的參數(shù),然后再進行遍歷??梢允褂?strong>$*和$@變量來訪問所有的變量,這兩個變量都能夠在單個變量中存儲所有的命令行參數(shù)。
    • $*變量會將命令行上提供的所有參數(shù)當作一個單詞保存,這個單詞包含了命令行中出現(xiàn)的每個參數(shù)值,基本上$*變量會將這些參數(shù)視為一個整體;
    • $@變量會將命令行上提供的所有參數(shù)當成同一個字符串中的多個獨立的單詞,這個就可以通過遍歷所有的參數(shù)值,得到每個參數(shù)。通常通過for命令來實現(xiàn)。
  • 兩個變量的具體功能,如下例所示:
    [njust@njust tutorials]$ ./bar12.sh  1 3 4 5 2
    Using the $* method: 1 3 4 5 2
    Using the $@ method: 1 3 4 5 2
    
  • 兩個變量的具體區(qū)別,如下例所示:
    #!/bin/bash
    
    count=1
    
    for param in "$*"
    do
        echo "\$* parameter #$count = $param"
        count=$[ $count + 1 ]
    done
    
    echo
    echo
    
    cnt=1
    for param in "$@"
    do
        echo "\$@ parameter #$cnt = $param"
        cnt=$[ $cnt + 1 ]
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar13.sh Curry Harden Durant James
    $* parameter #1 = Curry Harden Durant James
    
    
    $@ parameter #1 = Curry
    $@ parameter #2 = Harden
    $@ parameter #3 = Durant
    $@ parameter #4 = James
    

3.移動變量

  • bash shell的shift命令能夠用來操作命令行參數(shù),shift命令會根據(jù)它們的相對位置來移動命令行參數(shù)。默認情況下,它會將每個參數(shù)變量向左移動一個位置。所以,變量$3的值會移動$2,變量$2的值會移到$1中,變量$1的值會被刪除。但是,變量$0的值不會被改變,因為它是程序名。通過測試第一個參數(shù)值的長度執(zhí)行了一個while循環(huán),當?shù)谝粋€參數(shù)的長度為零時,循環(huán)結束。測試完第一個參數(shù)后,shift命令會將所有參數(shù)的位置移動一個位置,如下例所示:
    #!/bin/bash
    
    
    count=1
    while [ -n "$1" ]
    do
        echo "Parameter #$count = $1"
        count=$[ $count + 1 ]
        shift
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar14.sh Curry Harder Durant James
    Parameter #1 = Curry
    Parameter #2 = Harder
    Parameter #3 = Durant
    Parameter #4 = James
    
  • 也可以一次性移動多個位置,只需要給shift命令提供一個參數(shù),指明要移動的位置數(shù)就行。如下例所示:
    #!/bin/bash
    
    echo "The original parameters: $*"
    shift 2
    echo "Here's the new first parameter: $1"
    
    # 結果
    [njust@njust tutorials]$ ./bar15.sh  3 4 253 5 38
    The original parameters: 3 4 253 5 38
    Here's the new first parameter: 253
    

4.處理選項

  • 選項是跟在單折線后面的單個字母,它能改變命令的行為。下面將介紹3種在腳本中處理選項的方法。
4.1 查找選項
  • 處理簡單選項:在提取每個單獨參數(shù)時,用case語句來判斷某個參數(shù)是否為選項。如下例所示:
    #!/bin/bash
    
    
    while [ -n "$1" ]
    do
        case "$1" in
            -a) echo "Found the -a option";;
            -b) echo "Found the -b option";;
            -c) echo "Found the -c option";;
            *) echo "$1 is not an option";;
        esac
        shift
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar16.sh -a -b -c -d
    Found the -a option
    Found the -b option
    Found the -c option
    -d is not an option
    
  • 分離參數(shù)和選項:在shell腳本中同時使用選項和參數(shù)的情況,Linux中處理這個問題的標準方法是用特殊字符來將兩者分開,該字符會告訴腳本何時選項結束以及普通參數(shù)何時開始。對Linux來說,這個特殊字符是--,shell會用雙破折線來表明選項列表已經(jīng)結束。在雙破折線后,腳本就可以放心將剩下的命令行參數(shù)當作參數(shù),而不是選項。如下例所示:
    #!/bin/bash
    
    while [ -n "$1" ]
    do
        case "$1" in
            -a) echo "Found the -a option";;
            -b) echo "Found the -b option";;
            -c) echo "Found the -c option";;
            --) shift
                break;;
            *) echo "$1 is not an option";;
        esac
        shift
    done
    
    count=1
    
    for param in $@
    do
        echo "Parameter #$count: $param"
        count=$[ count + 1 ]
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar17.sh -c -a -b -- test1 test2 test3
    Found the -c option
    Found the -a option
    Found the -b option
    Parameter #1: test1
    Parameter #2: test2
    Parameter #3: test3
    
  • 處理帶值的選項:有些選項會帶上一個額外的參數(shù)值,如./bar666.sh -a test1 -b -c -d test2。當命令行選項要求額外的參數(shù)時,腳本必須能檢測到并正確處理。如下例所示:
    #!/bin/bash
    
    
    while [ -n "$1" ]
    do
        case "$1" in
            -a) echo "Found the -a option";;
            -b) param="$2"
                echo "Found the -b option,with parameter value $param."
                shift;;
            -c) echo "Found the -c option";;
            --) shift
                break;;
            *) echo "$1 is not an option";;
        esac
        shift
    done
    
    
    count=1
    for param in "$@"
    do
        echo "Parameter #$count: $param"
        count=$[ $count + 1 ]
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar19.sh -a -b test1 -f -- demo1 demo2
    Found the -a option
    Found the -b option,with parameter value test1.
    -f is not an option
    Parameter #1: demo1
    Parameter #2: demo2
    
4.2 使用getopt命令
  • getopt命令是一個在處理命令行選項和參數(shù)時非常方便的工具,它能識別命令行參數(shù),從而在腳本中解析它們時更方便。
  • 命令格式:getopt命令可以接受一系列任意形式的命令行選項和參數(shù),并自動轉換成適當?shù)母袷?,具體命令格式如下所示:
    getopt optstring parameters
    
  • optstring定義了命令行有效的選項字母,還定義了哪些選項字母需要參數(shù)值。optstring中列出了要在腳本中用到的每個命令行選項字母。然后,在每個需要參數(shù)值的選項字母后加一個冒號。注意:getopt命令有一個更高級的版本即getopts,注意兩者的區(qū)別。具體實例如下所示:
    [njust@njust tutorials]$ getopt ab:cd -a -b test1 -cd test2 test3
    -a -b test1 -c -d -- test2 test3
    
  • 上述實例中,optstring定義了四個有效選項字母:a、b、c、d。字母b后面的冒號表示b選項需要一個參數(shù)值。注意:getopt命令會將-cd選項分成兩個單獨的選項,并插入雙破折線來分隔行中的額外參數(shù)。
  • 如果指定了一個不在abcd選項中的參數(shù),默認情況下,getopt命令會產(chǎn)生一條錯誤的信息。如下所示:
    [njust@njust tutorials]$ getopt ab:cd -a -b test1 -cdf test2 test3
    getopt:無效選項 -- f
    -a -b test1 -c -d -- test2 test3
    
  • 如果需要忽略這條錯誤信息,可以在命令后加上-q選項,如下所示:
    [njust@njust tutorials]$ getopt -q ab:cd -a -b test1 -cdf test2 test3
    -a -b 'test1' -c -d -- 'test2' 'test3'
    
  • 在腳本中使用getopt:用getopt命令生成的格式后的版本來替換自己已有的命令行選項和參數(shù),用set命令能夠做到。set命令使用的方法如下:
    set -- $(getopt -q ab:cd "$@")
    
  • 利用上述方法,可以幫我們處理命令行參數(shù)的腳本。如下例所示:
    #!/bin/bash
    
    
    set -- $(getopt -q ab:cd "$@")   # 注意此條語句!?。?
    while [ -n "$1" ]
    do
        case "$1" in
            -a) echo "Found the -a option";;
            -b) param="$2"
                echo "Found the -b option,with parameter value $param."
                shift;;
            -c) echo "Found the -c option";;
            --) shift
                break;;
            *) echo "$1 is not an option";;
        esac
        shift
    done
    
    
    count=1
    for param in "$@"
    do
        echo "Parameter #$count: $param"
        count=$[ $count + 1 ]
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar20.sh -ac  # 合并選項情況下也能處理!
    Found the -a option
    Found the -c option
    
  • 但是,getopt命令也存在一個小問題。它并不擅長處理帶空格和引號的參數(shù)值。它會將空格當成參數(shù)分隔符,而不是根據(jù)雙引號將兩者看成一個參數(shù),解決方法是使用更高級的getopts命令
    [njust@njust tutorials]$ ./bar20.sh -a -b test1 -c "test2 test3" test4
    Found the -a option
    Found the -b option,with parameter value 'test1'.
    Found the -c option
    Parameter #1: 'test2
    Parameter #2: test3'
    Parameter #3: 'test4'
    
4.3 使用更高級的getopts命令
  • getopts命令是shell中的內建命令,它比getopt命令多了一些擴展功能。getopt命令將命令行上選項和參數(shù)處理后只生成一個輸出,而getopts命令能夠和已有的shell參數(shù)變量配合使用。每次調用它時,它一次只處理命令行上檢測到的一個參數(shù),處理完所有的參數(shù)后,它會退出并返回一個大于0的退出狀態(tài)碼,這讓它非常適合用解析命令行所有參數(shù)的循環(huán)中。getopts命令的格式如下:
    getopts optstring variable
    
  • optstring值類似于getopt命令中的那個,getopts命令將當前參數(shù)保存在命令行中定義的variable中。getopts命令會用到兩個環(huán)境變量,如果選項需要跟一個參數(shù)值,OPTARG環(huán)境變量就會保存這個值,OPTIND環(huán)境變量保存了參數(shù)列表中getopts正在處理的參數(shù)位置,這樣你就能在處理完選項后繼續(xù)處理其他命令行參數(shù)了。如下例所示:
    #!/bin/bash
    
    
    while getopts :ab:c opt
    do
        case "$opt" in
            a) echo "Found the -a option";; # 注意:getopts命令在解析命令行選項時會移除開頭的單破折線,所以在case定義中不用單破折線!
            b) echo "Found the -b option,with value $OPTARG";;
            c) echo "Found the -c option";;
            *) echo "Unknown option: $opt";;
        esac
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar21.sh  -ab test1 -c
    Found the -a option
    Found the -b option,with value test1
    Found the -c option
    
    
  • getopts命令的優(yōu)點之一是可以在參數(shù)值中包含空格,如下例所示:
    [njust@njust tutorials]$ ./bar21.sh  -b "test1 test2" -a
    Found the -b option,with value test1 test2
    Found the -a option
    

getopts命令的另一個優(yōu)點是將選項字母和參數(shù)值放在一起使用,而不用加空格。如下例所示:
[njust@njust tutorials]$ ./bar21.sh -abdemo1 Found the -a option Found the -b option,with value demo1

  • 此外,getopts命令還可以將命令行上找到的所有未定義的選項統(tǒng)一輸出為問號,如下例所示:
    [njust@njust tutorials]$ ./bar21.sh  -acdf
    Found the -a option
    Found the -c option
    Unknown option: ?
    Unknown option: ?
    
  • getopts命令知道何時停止處理選項,并將參數(shù)留給你處理。在getopts處理每個選項時,它會將OPTIND環(huán)境變量值加1,在getopts完成處理時,使用shift命令和OPTIND值來移動參數(shù)。如下例所示:
    #!/bin/bash
    
    
    while getopts :ab:cd opt
    do
        case "$opt" in
            a) echo "Found the -a option";;
            b) echo "Found the -b option,with value $OPTARG";;
            c) echo "Found the -c option";;
            d) echo "Found the -d option";;
            *) echo "Unknown option: $opt";;
        esac
    done
    
    shift $[ $OPTIND - 1 ]
    
    count=1
    for param in "$@"
    do
        echo "Parameter $count:$param"
        count=$[ $count + 1 ]
    done
    
    # 結果
    [njust@njust tutorials]$ ./bar22.sh -a -b test1 -d test2 test3 test4
    Found the -a option
    Found the -b option,with value test1
    Found the -d option
    Parameter 1:test2
    Parameter 2:test3
    Parameter 3:test4
    

5.將選項標準化

  • 下面是Linux中常用到的一些命令行選項的含義。
    選項                               含義
    -a                             顯示所有對象
    -c                             生成一個計數(shù)
    -d                             指定一個目錄
    -e                             擴展一個對象
    -f                             指定讀入數(shù)據(jù)的文件
    -h                             顯示命令的幫助信息
    -i                             忽略文本大小寫
    -l                             產(chǎn)生輸出的長格式版本
    -n                             使用非交互模式
    -o                             將所有輸出重定向到指定的輸出文件
    -q                             以安靜模式運行
    -r                             遞歸地處理目錄和文件
    -s                             以安靜模式運行
    -v                             生成詳細輸出
    -x                             排除某個對象
    -y                             對所有問題回答yes
    

6.獲得用戶輸入

  • 盡管命令行選項和參數(shù)是從腳本用戶處獲得輸入的一種重要方式,但是有時候腳本的交互性還需要更強一些。例如在運行腳本時問一個問題,并等待運行腳本的人來回答,bash shell為此提供了read命令
6.1 基本的讀取
  • read命令從標準輸入或另一個文件描述符中接收輸入。在收到輸入后,read命令會將數(shù)據(jù)放進一個變量,如下例所示:
    #!/bin/bash
    
    
    echo -n "Please Enter your name: "  # -n選項不會在字符串末尾輸出換行符,允許腳本用戶緊跟其后輸入數(shù)據(jù),而不是在下一行輸入!
    read name
    echo "Hello $name,welcome to my home."
    
    # 結果
    [njust@njust tutorials]$ ./bar23.sh 
    Please Enter your name: Curry   # 自己輸入的!
    Hello Curry,welcome to my home.
    
  • read命令包含了-p選項,它允許你直接在read命令行指定提示符,如下例所示:
    #!/bin/bash
    
    
    read -p "Please Enter your age: " age
    days=$[ $age * 365 ]
    echo "That makes you over $days days old"
    
    # 結果
    [njust@njust tutorials]$ ./bar24.sh 
    Please Enter your age: 28
    That makes you over 10220 days old
    
  • 也可以在read命令行中不指定變量,read命令會將它收到的任何數(shù)據(jù)都放進特殊環(huán)境變量REPLY中,REPLY環(huán)境變量會保存輸入的所有數(shù)據(jù),可以在shell腳本中像其他變量一樣使用。如下例所示:
    #!/bin/bash
    
    
    read -p "Enter your name: "
    echo "Hello $REPLY,welcome to NewYork."
    
    # 結果
    [njust@njust tutorials]$ ./bar25.sh 
    Enter your name: Stephen Curry
    Hello Stephen Curry,welcome to NewYork.
    
6.2 超時
  • 使用read命令時一定要注意,腳本很可能會一直等待用戶的輸入。如果不管是否有數(shù)據(jù)輸入,腳本都必須繼續(xù)執(zhí)行,可以使用-t選項來指定一個計數(shù)器。-t選項指定了read命令等待輸入的秒數(shù),當計數(shù)器超時后,read命令會返回一個非零退出狀態(tài)碼,如下例所示:
    #!/bin/bash
    
    
    if read -t 5 -p "Please enter your name: " name
    then
        echo "Hello $name,welcome to NewYork."
    else
        echo 
        echo "Sorry, it's wrong!"
    fi
    
    # 結果
    [njust@njust tutorials]$ ./bar26.sh 
    Please enter your name: 
    Sorry, it's wrong!
    
  • 也可以不對輸入過程計時,而是讓read命令來統(tǒng)計輸入的字符數(shù),當輸入的字符達到預設的字符數(shù)時,就自動退出,將輸入的數(shù)據(jù)賦值給變量。如下例所示:
    #!/bin/bash
    
    
    read -n1 -p "Do you want to continue [Y/N]? " answer
    case $answer in
        Y | y) echo
                echo "Fine,continue on...";;
        N | n) echo
                echo "Ok,goodbye"
                exit;;
    esac
    echo "This is the end of the script"
    
    
    # 結果
    [njust@njust tutorials]$ ./bar27.sh 
    Do you want to continue [Y/N]? Y
    Fine,continue on...
    This is the end of the script
    
  • 上述例子中,-n選項與值1一起使用,它告訴read命令在接收單個字符后退出。只要按下單個字符后,read命令就會接收輸入并將它傳給變量,無需按下回車鍵。
6.3 隱藏方式讀取
  • 有時候需要從用戶輸入處得到輸入,但又不能在屏幕中顯示輸入。其中典型的例子就是輸入的密碼,此外還有很多其他需要隱藏的數(shù)據(jù)類型。-s選項可以避免在read命令中輸入的數(shù)據(jù)出現(xiàn)在屏幕上,如下例所示:
    #!/bin/bash
    
    
    read -s -p "Enter you password: " passwd
    echo
    echo "Is your password really $passwd? "
    
    # 結果
    [njust@njust tutorials]$ ./bar28.sh 
    Enter you password: 
    Is your password really 12345? 
    
6.4 從文件中讀取
  • 可以用read命令來讀取Linux系統(tǒng)上文件中保存的數(shù)據(jù),每次調用read命令,它都會從文件中讀取一行文本。當文本中沒有內容時,read命令會退出并返回非零退出狀態(tài)碼。注意:最難的部分是將文件中的數(shù)據(jù)傳給read命令,最常見的方法是對文件使用cat命令,將結果通過管道直接傳給含有read命令的while命令。如下例所示:
    #!/bin/bash
    
    count=1
    
    cat demodemo | while read line
    do
        echo "Line $count: $line"
        count=$[ $count + 1 ]
    done
    echo "Finished processing the file"
    
    # 結果
    [njust@njust tutorials]$ ./bar29.sh 
    Line 1: The quick brown dog jumps over the lazy fox.
    Line 2: This is a test, this is only a test.
    Line 3: O Romeo, Romeo!Wherefore art thou Romeo?
    Finished processing the file
    

7.資料下載

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容