Unix/Linux指令碼中“set -e”的作用

來源:互聯網
上載者:User

Unix/Linux指令碼中“set -e”的作用 -----------------------------------------------------------#!/bin/bashset -ecommand 1command 2...exit 0----------------------------------------------------------Every script you write should include set -e at the top. This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit. 你寫的每個指令碼都應該在檔案開頭加上set -e,這句語句告訴bash如果任何語句的執行結果不是true則應該退出。這樣的好處是防止錯誤像滾雪球般變大導致一個致命的錯誤,而這些錯誤本應該在之前就被處理掉。如果要增加可讀性,可以使用set -o errexit,它的作用與set -e相同。 Using -e gives you error checking for free. If you forget to check something, bash will do it for you. Unfortunately it means you can't check $? as bash will never get to the checking code if it isn't zero. There are other constructs you could use:使用-e協助你檢查錯誤。如果你忘記檢查(執行語句的結果),bash會幫你執行。不幸的是,你將無法檢查$?,因為如果執行的語句不是返回0,bash將無法執行到檢查的代碼。你可以使用其他的結構: [plain] command  if [ "$?"-ne 0]; then       echo "command failed";       exit 1;   fi   could be replaced with能夠被代替為[plain] command || { echo "command failed"; exit 1; }   or或者[plain] if ! command; then       echo "command failed";       exit 1;   fi    What if you have a command that returns non-zero or you are not interested in its return value? You can use command || true, or if you have a longer section of code, you can turn off the error checking, but I recommend you use this sparingly.如果你有一個命令返回非0或者你對語句執行的結果不關心,那你可以使用command || true,或者你有一段很長的代碼,你可以關閉錯誤檢查(不使用set -e),但是我還是建議你保守地使用這個語句。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.