将stderr和stdout重定向到2个不同的变量 注意:

问题描述

是否可以将stdout和stderr转换为2个不同的变量?

代码

#!/bin/bash
A=1
B=0

echo -n "Attempting to divide......"

#This will cause a Division by zero error
#Also,the below is pseudocode ONLY. It is not valid bash Syntax
RESULT,ERR_MSG=$((A/B))

if [[ $? == 0 ]]
then
    echo "[SUCCESS]"
else
    echo "[FAIL]"
    echo "$ERROR_MSG"
fi

解决方法

有可能,但并不漂亮。

最好的解决方案是使用@shellter注释中建议的临时文件。这需要一点注意,以确保临时文件不会覆盖其他任何文件并正确清理,但是至少应该可靠。

但是,尽管我不能坦率地说我可以百分百确定自己已经涵盖了所有可能的极端情况,但仍可以使用bash进行操作[注1]。以下函数运行命令并将其stdout和stderr记录到两个环境变量中,它们的名称作为参数提供。它有两种操作模式:

  • 如果提供的参数少于三个,则第一个参数命名将接收stdout和stderr的变量。参数分别默认为outerr。该命令必须提供给函数的stdin,并将在单独的bash shell中运行。

  • 如果至少有三个参数,则前两个参数如上命名变量,其余参数作为外部命令执行。 (如果要运行管道或bash函数,则不能使用此版本。)

如果您希望能够使用任意bash命令执行此操作,那么从stdin读取命令将是解决方案,但是子bash子进程与子shell并不相同;您需要确保export bsplit () { local -a cmd=("${@:3}") if ! ((${#cmd})); then cmd=("$SHELL"); fi local outerr=$( "${cmd[@]}" 2>&1 > >( IFS= read -rd '' s printf '%s|%d' "$s" ${#s} 1>&2 ) ) local n=${outerr##*|} outerr=${outerr%|*} declare -n out_=${1:-out} err_=${2:-err} if ((n)); then out_=${outerr: -$n} err_=${outerr:0:-$n} else out_="" err_=$outerr fi } 您需要在命令中使用的任何变量和函数(不幸的是,您无法导出bash数组)。您可以以here-string或here-doc的形式提供输入;对于需要用引号引起来的命令,您可能会发现使用带引号的here-doc更简单,如下所示。

在大多数情况下,您可能希望使用运行指定命令的版本,但请记住,在调用函数之前先执行命令的扩展,因此所产生的错误将不会捕获在error变量中。 / p>

功能如下:

    local outerr=$(
        "${cmd[@]}" 2>&1 > >(
             IFS= read -rd '' s
             printf '%s|%d' "$s" ${#s} 1>&2
        )
    )

函数的心脏是命令的调用:

2>&1

第一个重定向(> >(...))会将stderr输出直接发送到命令替换中,该命令替换将在环境变量中捕获。第二个重定向(printf)将stdout输出传递到一个子外壳,该子外壳读取整个输出并在将其发送到stderr之前附加其长度(以字节为单位)。请注意,发送给它的stderr是先前重定向的那个,它将转到命令替换。此舞步确保在错误输出之后发送常规输出; # Execute bash arithmetic substitutions using a here-string $ bsplit <<<'echo $((1/1)); echo $((1/0))' $ echo "$out" 1 $ echo "$err" /bin/bash: line 1: 1/0: division by 0 (error token is "0") # Here's a script being executed in a quoted here-doc to avoid quoting issues: $ bsplit <<"EOS" > cat <(printf %s "Hello,") <(printf '%s!' " world") > not a command > EOS $ echo "$out" Hello,world! $ echo "$err" /bin/bash: line 2: not: command not found # And a more typical case where it just runs a command: $ bsplit out err ls -l a_file a_nonexistent_file $ echo "$out" -rw-rw-r-- 1 rici rici 0 Sep 6 13:04 a_file $ echo "$err" ls: cannot access 'a_nonexistent_file': No such file or directory 不会执行,直到原始的stdout被正在运行的命令终止而关闭为止,此时所有命令的错误输出将已经发送完毕。

该函数的其余部分仅将连接的输出分成两部分,使用末尾的长度指示器找到分割点。

一些例子:

v1 <- tapply(start_r,cs1,na.omit)

注意:

  1. 如果您发现没有盖角的情况,请在评论中告诉我。没有承诺,尽管:-)