stderr 重定向_如何判断是否将其STDERR重定向到Linux上Bash脚本中的文件?

stderr 重定向

Within a Bash script, how to judge whether its STDERR is redirected to a file in Bash on Linux?

在Bash脚本中,如何判断其STDERR是否已重定向到Linux上Bash中的文件?

For example,

例如,

./script.sh /tmp/log 2>&1

Can script.sh detect that its STDERR is redirected? Knowing the destination file is better.

script.sh是否可以检测到其STDERR被重定向? 了解目标文件会更好。

To test whether a script’s STDERR (or STDOUT) is redirected to a file, check by

要测试脚本的STDERR(或STDOUT )是否重定向到文件,请通过

[[ -f /dev/stderr ]]

A process’ STDOUT and STDERR are /dev/stdout and /dev/stderr and testing them with -f in Bash can judge whether they are redirected to files.

进程的STDOUT和STDERR是/dev/stdout/dev/stderr ,在Bash中用-f测试它们可以判断它们是否重定向到文件

An example:

一个例子:

$ cat check-stdout-stderr.sh 
#!/bin/bash

# Author: Eric Zhiqiang Ma

[[ -f /dev/stderr ]] && echo "STDERR is a file: $(readlink -f /dev/stderr)"
[[ -f /dev/stdout ]] && echo "STDOUT is a file: $(readlink -f /dev/stdout)"

Tries:

尝试:

$ ./check-stdout-stderr.sh

outputs nothing.

什么都不输出。

$ ./check-stdout-stderr.sh >/tmp/a
$ cat /tmp/a
STDOUT is a file: /proc/25141/fd/pipe:[2397415]

and

$ ./check-stdout-stderr.sh >/tmp/a 2>/tmp/b
$ cat /tmp/a
STDERR is a file: /tmp/b
STDOUT is a file: /proc/25159/fd/pipe:[2393867]

The interesting part is that STDOUT redirecting is implemented as a pipe (with caching, I guess).

有趣的是STDOUT重定向是通过管道实现的(我想是带有缓存的)。

Answered by Eric Z Ma.
埃里克·马(Eric Z Ma)回答。

翻译自: https://www.systutorials.com/how-to-judge-whether-its-stderr-is-redirected-to-a-file-in-a-bash-script-on-linux/

stderr 重定向

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值