假设我有这样的脚本:
logfile=$1
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实际上是stdout?
为什么?我希望有一个脚本可以将其部分输出打印到stdout,或者(可选)打印到文件中。
您可能会问:“为什么不删除>> $logfile部件,然后在您想要写入文件时使用./script >> filename调用它呢?”
嗯,因为我只想对一些输出消息执行“可选重定向”的操作。在上面的例子中,应该只影响第二条消息。
发布于 2015-07-24 21:55:23
如果您的操作系统是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 $1 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"放在应该登录到文件的每一行上,后者会重新打开文件以便对每个命令进行输出。
https://stackoverflow.com/questions/31620328
复制相似问题