簡體   English   中英

shell和命令替換中的“set -e”

[英]“set -e” in shell and command substitution

在shell腳本中, set -e通常用於通過在腳本執行的某些命令以非零退出代碼退出時停止腳本來使其更加健壯。

通過添加|| true ,通常很容易指定您不關心某些成功的命令 || true

當您真正關心返回值時會出現問題,但不希望腳本停止非零返回代碼,例如:

output=$(possibly-failing-command)
if [ 0 == $? -a -n "$output" ]; then
  ...
else
  ...
fi

這里我們要檢查退出代碼(因此我們不能在命令替換表達式中使用|| true )並獲取輸出。 但是,如果命令替換命令失敗,整個腳本將因set -e而停止。

有沒有干凈的方式,以防止腳本停在這兒沒有你重置-e ,又把它放回后來呢?

是的,在if語句中內聯進程替換

#!/bin/bash

set -e

if ! output=$(possibly-failing-command); then
  ...
else
  ...
fi

命令失敗

$ ( set -e; if ! output=$(ls -l blah); then echo "command failed"; else echo "output is -->$output<--"; fi )
/bin/ls: cannot access blah: No such file or directory
command failed

指揮工作

$ ( set -e; if ! output=$(ls -l core); then echo "command failed"; else echo "output is: $output"; fi )
output is: -rw------- 1 siegex users 139264 2010-12-01 02:02 core

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM