2016-09-30 173 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,这是一个偏好问题。有些人可能会认为这是一种反模式。但答案中使用的风格对我来说很清楚。 –