if、until、while中的test-commands

exit status

上一個命令執行完後,退出時返回的狀態值。html

0 表示成功;非0表示失敗。正則表達式

在命令行中能夠打印查看上一個狀態值express

$ echo $?

依賴於 exit status 的 if、until、while

  • until 的語法:bash

    until test-commands; do
      consequent-commands; 
    done
  • while 的語法命令行

    while test-commands; do
      consequent-commands; 
    done
  • if 的語法code

    if test-commands; then
      consequent-commands;
    [elif more-test-commands; then
      more-consequents;]
    [else alternate-consequents;]
    fi

test-commands 執行以後,ifuntilwhile 依賴於它的 exit statushtm

  1. 爲 0 時,if 執行;
  2. 爲 1 時,until 執行;
  3. 爲 0 時,while 執行。

test-commands 包含的狀況

一組或多組管道組成 test-commands

  1. 多組管道之間能夠由 ;, &, &&, 或 ||分隔,
  2. ;, &, 或 換行 結束;
  3. exit status 由最後一組管道的 exit status 決定;
  4. 一個或多個命令組成一個管道,由||& 分隔,由最後一個命令的 exit status 決定管道的 exit status
  5. 通常而言,單個命令執行成功,狀態值爲0。get

    // 文件test
    #!/usr/bin/bash
    if ls;ls;then
      echo ==111==
    else
      echo ==222==
    fi
    
    if ls;lss;then
      echo ==333==
    else
      echo ==444==
    fi
    
    $ ./test
    test  test_1  test1
    test  test_1  test1
    ==111==
    test  test_1  test1
    ./test: line 8: lss: command not found
    ==444==

(( 算術表達式 )) 組成 test-commands

let "expression"it

加減乘除等,計算出來的值爲0,exit status 值爲1;計算出來的值爲非0,exit status 值爲0;io

// 文件 test
#!/usr/bin/bash
if ((1+1));then
  echo ==111==
else
  echo ==222==
fi

if ((1-1));then
  echo ==333==
else
  echo ==444==
fi

$ ./test
==111==
==444==

[[ 條件表達式 ]] 組成 test-commands

// 文件 test
#!/usr/bin/bash
if [[ str1 == str* ]];then
  echo ==111==
else
  echo ==222==
fi

if [[ 'str1' = 'str2' ]];then
  echo ==333==
else
  echo ==444==
fi

$ ./test
==111==
==444==

[ 條件表達式 ] 組成 test-commands

test 表達式,相似 [[ 條件表達式 ]]

// 文件 test
#!/usr/bin/bash
if [ str1 == str* ];then
  echo ==111==
else
  echo ==222==
fi

if [ 'str1' = 'str2' ];then
  echo ==333==
else
  echo ==444==
fi

$ ./test
==222==
==444==

[[]] 與 [] 的區別

  1. [[]] 中,不會進行分詞、文件名擴展。
  2. [[]] 中,==!= 右側的操做數,被當作是正則表達式。(= 等同於 ==

參考

相關文章
相關標籤/搜索