将带有 stdout 的命令传递给 bash 函数

将带有 stdout 的命令传递给 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:
-----------------

-----------------

如何将带有重定向或管道的命令作为命令传递给 bash 中的另一个函数?

非常感谢您的帮助和提示!我不知道如何实现这一点,或者这是否可行?

答案1

来自bash 手册页

   *      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>

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

相关内容