传递命令与标准输出到一个bash函数

好的,这是交易。 我有一个bash脚本,如下所示。 剧本只是向你展示我的意思..它可能看起来束缚,但正是我所需要的:

#/bin/bash runcommand () { message="$1" shift echo "$message" $@ > /tmp/logfile if [ $? -gt 0 ]; then cat /tmp/logfile fi } runcommandwrapper () { wrapperoptions="$1" shift $* } rm -f /tmp/test ; rm -f /tmp/logfile runcommand "echo into file" echo "SUCCESS" > /tmp/test echo "-----------------" echo "test file:" echo "-----------------" cat /tmp/test echo "-----------------" echo echo "-----------------" echo "logfile file:" echo "-----------------" cat /tmp/logfile echo "-----------------" echo echo echo rm -f /tmp/test ; rm -f /tmp/logfile runcommand "echo into file" 'echo "SUCCESS" > /tmp/test' echo "-----------------" echo "test file:" echo "-----------------" cat /tmp/test echo "-----------------" echo echo "-----------------" echo "logfile file:" echo "-----------------" cat /tmp/logfile echo "-----------------" echo 

这工作

 runcommand "running command mount" mount 

这不起作用

 runcommand "running command fdisk" fdisk > /tmp/fdiskoutput 

在这种情况下,引号中的文本不会被视为包装脚本中的整个参数。 试试看,你会明白我的意思。 – >已解决

所以运行上面的脚本返回:

 ----------------- test file: ----------------- echo into file ----------------- ----------------- logfile file: ----------------- SUCCESS ----------------- echo into file ----------------- test file: ----------------- cat: /tmp/test: No such file or directory ----------------- ----------------- logfile file: ----------------- "SUCCESS" > /tmp/test ----------------- 

但预期的结果是:

 ----------------- test file: ----------------- SUCCESS ----------------- ----------------- logfile file: ----------------- ----------------- echo into file ----------------- test file: ----------------- SUCCESS ----------------- ----------------- logfile file: ----------------- ----------------- 

我怎么能通过命令redirect或pipe道作为命令到bash中的另一个function?

和帮助和提示将非常感激! 我不知道如何得到这个工作,或者如果这是可能的呢?

从bash的manpage :

  * Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. <snip> @ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... <snip> 

因此,您需要使用"$@" (包括双引号)而不是$*因为您要保留原始参数引用。