一 基本腳本

  1. 執(zhí)行數(shù)學(xué)運(yùn)算

    • expr
      expr 5 * 2
    • 方括號(hào) $[]
      $[5 * 2]
      缺點(diǎn):只支持整數(shù)運(yùn)算
    • bc運(yùn)算
      variable=$(echo "scale=4; 3.44/5" | bc)
  2. 執(zhí)行命令
    $()

  3. 處理參數(shù)

    • $#
      參數(shù)個(gè)數(shù)
    • $*
      所有的參數(shù)(作為一個(gè)變量)
    • $@
      所有的參數(shù)(作為多個(gè)變量)
    • $0 $1 $2 $3
      各個(gè)參數(shù)
    • shift
      移動(dòng)變量
      #!/bin/bash
      while [ -n "$1" ]
      do
        case "$1" in
        -a) echo "Found -a option";;
        -b) echo "Found -b option";;
         *) echo "$1 is not a option"
        esac
        shift
      done
      
    • getopts獲取參數(shù)
  4. 獲取輸入 read

    • read -p "message" key
    • -t 指定超時(shí)退出
    • -s 不會(huì)將用戶輸入顯示出來(lái),比如輸入密碼
  5. 呈現(xiàn)數(shù)據(jù)

    1. 標(biāo)準(zhǔn)文件描述符
      0:stdin 標(biāo)準(zhǔn)輸入
      1:stdout 標(biāo)準(zhǔn)輸出
      2:stderr 標(biāo)準(zhǔn)錯(cuò)誤
    2. 將錯(cuò)誤重定向到日志文件
      ls -al aaa 2> error.log
    3. 腳本中,臨時(shí)將錯(cuò)誤消息重定向
      echo "this is an error message" >&2
      需要在文件描述符前邊加"&"
      #!/bin/bash
      echo "This is an error message"  >&2
      echo "This is an normal message"
      
      正常運(yùn)行時(shí),屏幕兩條消息均輸出了。這是因?yàn)檎G闆r下,stderr指向的和stdout是同一個(gè)地方。
      如果運(yùn)行時(shí)將錯(cuò)誤重定向,屏幕就只有一條輸出了。
      ./test_error.sh 2> error.log
    4. 腳本中,永久重定向,使用exec
      #!/bin/bash
      echo "This you can see"
      
      exec 2>error.log
      echo "This is in error.log" >&2
      
      exec 1>info.log
      echo "This is in info.log"
      
    5. 阻止腳本輸出,將輸出重定向到null
      ls -al > /dev/null
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容