2015-12-03 38 views
1

我寫了一個函數來檢查一個命令是否成功執行,如果沒有,則拋出一個錯誤。如何發送帶有消息的命令以成功回送bash函數?

assert_success() { 
    "$1" 
    if [[ $? == 0 ]]; then 
     echo "$2" 
    fi 
} 

說我有以下命令給定的錯誤執行:

assert_success <command> <error_message> 

因此,基本上,像下面這樣:

assert_success $(mkdir blah) "This worked" 

不過,我得到a.sh: line 3: This worked: command not found

如何讓echo在此處正確工作?

+0

閱讀[我想在一個變量把一個命令,但是複雜的情況下總是失敗!(HTTP ://mywiki.wooledge.org/BashFAQ/050)。 – chepner

回答

1

問題是在這個調用:

assert_success $(mkdir blah) "This worked"` 

傳遞mkdir命令的輸出,而不是mkdir命令本身。而且由於mkdir輸出是空的,它是加引號"This worked"成爲$1你的函數裏面,你會得到錯誤:This worked: command not found

我建議你有你的功能是這樣的:

assert_success() { 
    msg="$1" 
    shift 
    if [email protected]; then 
     echo "$msg" 
    fi 
} 

,並調用該函數:

assert_success "This worked" mkdir blah 
1

除了我在評論中的鏈接中討論的問題,不需要這樣的功能。只需簡單地運行命令即可,然後使用&&運算符打印成功消息。比較

mkdir blah && echo "This worked" 

與任何

assert_success "mkdir blah" "This worked" 

或anubhava的解決方案

assert_success "This worked" mkdir blah