将回声或printf输出重定向到变量,该变量代表bash脚本中的std*流



在perl中,我通常会这样做:

...
if(exists($myLog))
{
    if( ! open($fhLog, '>>', $myLog))
    {
        print "[wrn] unable to open "$myLog", using stdout insteadn";
        $fhLog = *STDOUT;
    }
}
...

然后,在整个脚本中,我只使用:

print $fhLog "n[inf] started at $rndaten";

无论如何,知道它会转到文件或stdout

如何在bash中 echo "text" > $someVar取得相同的结果?

编辑:rhel7

上的bash 4.2

假设Bash 4.1或更新,您具有自动文件描述符验证,并且能够将变量重定向到FD数字:

#!/usr/bin/env bash
case $BASH_VERSION in
  ""|[0-3].*|4.0*) echo "ERROR: Bash 4.1 or newer is needed" >&2; exit 1;;
esac
logFd=2 ## default to logging to stderr
# if myLog variable exists, make logFd a file descriptor number open to it
[[ $myLog ]] && exec {logFd}>"$myLog"
echo "This will go to either the file or stderr" >&$logFd

有两个关键部分:

  • exec {variableName}>filename打开filename并将文件描述符分配给变量variableName。您可以适当地更改重定向操作员(转换为>><>等(。
  • >&$variableName重定向到variableName中存储的文件描述符。

使用旧版本的bash或与Posix SH的兼容性,您需要使用固定的FD号码:

#!/bin/sh
# here, we're using FD 3 for logging
if [ -n "$myLog" ]; then
  exec 3>"$myLog"
else
  exec 3>&2
fi
echo "This will go to either the file or stderr" >&3

最新更新