将输出写入 $file(允许它是标准输出)

Write output to $file (allowing it to be stdout)

假设我有这个脚本:

logfile=
echo "This is just a debug message indicating the script is starting to run..."

# Do some work...

echo "Results: x, y and z." >> $logfile

是否可以从命令行调用脚本以使 $logfile 实际上是标准输出?


为什么?我想要一个脚本,将其输出的 部分 打印到标准输出,或者可选地打印到文件。

"But why not remove the >> $logfile part and just invoke it with ./script >> filename when you want to write to a file?",你可能会问。

好吧,因为我只想对某些输出消息执行此 "optional redirect" 操作。在上面的示例中,只有第二条消息会受到影响。

如果您的操作系统是 Linux 或类似的符合约定的操作系统,请使用 /dev/stdout。或者:

#!/bin/bash

# works on bash even if OS doesn't provide a /dev/stdout
# for non-bash shells, consider using exec 3>&1 explicitly if  is empty
exec 3>${1:-/dev/stdout}

echo "This is just a debug message indicating the script is starting to run..." >&2
echo "Results: x, y and z." >&3

这也 大大 比将 >>"$filename" 放在应该记录到文件的每一行上更有效,后者会重新打开文件以在每个命令上输出。