2016-09-30 171 views
0

在一個bash文件s.sh中,我有一個Executor函數,我傳遞要執行的命令。每當某個命令不能按預期工作時,此功能將輸出該命令。Bash函數不執行輸入命令

Executor() 
{ 
    if ! $* 
    then 
     echo "$*" 
     exit 2 
    fi 
} 

現在我調用這個函數 -

Executor clangPath="Hello" make(這是用來設置clangPath變量的值,如「你好」,在生成文件)

這造成了一個錯誤 -

./s.sh: line 5: clangPath=Hello: command not found 
[./s.sh] Error: clangPath=Hello make 

但是執行這樣的命令一樣正常工作

if ! clangPath="Hello" make 
then 
    echo "HelloWorld!" 
fi 

看着錯誤後,我認爲有可能是用字符串的報價錯誤,所以我想

exitIfFail clangPath='"Hello"' make

即使這導致了一個錯誤 -

./s.sh: line 5: clangPath="Hello": command not found 
[./s.sh] Error: clangPath="Hello" make 

有什麼事情是錯誤的原因?

+0

你可以試試!/usr/bin/ksh $ * ...取決於你在哪裏和使用什麼shell?我沒有能力在這裏測試。 – FreudianSlip

+1

參見[Bash FAQ 050](http://mywiki.wooledge.org/BashFAQ/050)。 – chepner

+0

Eww,'$ *'...我認爲你拼錯了'「$ @」'。 –

回答

1

如果功能的目的是爲執行一些擊表達,然後通過eval打印錯誤信息,如果表達式失敗(返回非零狀態),那麼,有實現此的方式:

#!/bin/bash - 

function Executor() 
{ 
    eval "[email protected]" 

    if [ $? -ne 0 ] 
    then 
    echo >&2 "Failed to execute command: [email protected]" 
    exit 2 
    fi 
} 

$?變量保存先前執行的命令的退出狀態。所以我們檢查它是否非零。

另請注意我們如何將錯誤消息重定向到標準錯誤描述符。

用法:

Executor ls -lh /tmp/unknown-something 
ls: cannot access /tmp/unknown-something: No such file or directory 
Failed to execute command: ls -lh /tmp/unknown-something 


Executor ls -lh /tmp 
# some file listing here... 

[email protected]變量是比較合適的位置,爲eval解釋事物本身。請參閱$* and [email protected]

+1

['test $?'反模式](http://mywiki.wooledge.org/BashPitfalls#cmd.3B_.28.28_.21_.24.3F_.29.29_.7C.7C_die)是什麼?一個簡單的'如果! eval「$ @」'會更短,更清晰,並且與問題更加一致,'eval'$ @「&& return'仍然更簡單。 –

+0

@TobySpeight,這是一個偏好問題。有些人可能會認爲這是一種反模式。但答案中使用的風格對我來說很清楚。 –