【问题标题】:Write output to $file (allowing it to be stdout)将输出写入 $file(允许它是标准输出)
【发布时间】:2015-10-15 16:54:41
【问题描述】:

假设我有这个脚本:

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 实际上是标准输出?


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

“但是为什么不删除>> $logfile 部分并在您想写入文件时使用./script >> filename 调用它呢?”,您可能会问。

好吧,因为我只想为一些输出消息做这个“可选重定向”的事情。在上面的示例中,应该只影响第二条消息。

【问题讨论】:

    标签: bash shell unix command-line sh


    【解决方案1】:

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

    #!/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" 放在应该记录到文件的每一行上大大更有效,这会重新打开文件以在每个命令上输出。

    【讨论】:

    • 啊!这太棒了,谢谢!我可以在脚本中动态创建这些文件描述符吗? (据我了解,默认情况下只有 3 个——stdin、stdout 和 stderr)。
    • 同意,我愿意exec 3>${1:-/dev/stdout}
    • @bufh,授予,bash 将始终识别 /dev/stdout,即使没有文字 /dev 条目,但并非所有 shell 都是 bash,并且并非所有操作系统都有 /dev/stdout .
    • PS:非常感谢您的快速回复。太糟糕了,我还不能接受你的回答:P
    • @dsetton 是的,实际上在 Linux 上你会在/proc/$PID/fd/ 中看到你的程序的文件描述符,firefox 会有一百个......
    猜你喜欢
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2019-06-19
    相关资源
    最近更新 更多