对exec重定向感到困惑/ dev / null,我正确地做到了吗?

问题描述 投票:-1回答:1

背景

我正在训练自己在POSIX shell脚本,请回答时避免任何Bashism。谢谢。

我现在知道了,感谢Kusalanandaanswer,如何确定我的脚本是否以交互方式运行,即它是否连接到stdin


由于我很少使用execman page),我不确定我是否正确地做了以下想法?请详细说明。

如果脚本正在运行:

  • 交互式:将错误消息输出到stderr,否则在默认环境设置中运行。
  • 非交互式:在此示例中将所有输出重定向到/dev/null(最后我可能希望将stdoutstderr重定向到实际文件)。

# test if file descriptor 0 = standard input is connected to the terminal
running_interactively () { [ -t 0 ]; }

# if not running interactively, then redirect all output from this script to the black hole
! running_interactively && exec > /dev/null 2>&1

print_error_and_exit ()
{
    # if running interactively, then redirect all output from this function to standard error stream
    running_interactively && exec >&2

    ...
}
shell exec posix io-redirection
1个回答
0
投票

看来我很亲密。由于running_interactively函数按预期工作,我能够继续重定向到文件,如下所示。

我编辑了这个答案,以便有更多的代码可以重复使用。


#!/bin/sh

is_running_interactively ()
# test if file descriptor 0 = standard input is connected to the terminal
{
    # test if stdin is connected
    [ -t 0 ]
}

redirect_output_to_files ()
# redirect stdout and stderr
# - from this script as a whole
# - to the specified files;
#   these are located in the script's directory
{
    # get the path to the script
    script_dir=$( dirname "${0}" )

    # redirect stdout and stderr to separate files
    exec >> "${script_dir}"/stdout \
        2>> "${script_dir}"/stderr
}

is_running_interactively ||
# if not running interactively, add a new line along with a date timestamp
# before any other output as we are adding the output to both logs
{
    redirect_output_to_files
    printf '\n'; printf '\n' >&2
    date; date >&2
}

print_error_and_exit ()
{
    # if running interactively redirect all output from this function to stderr
    is_running_interactively && exec >&2
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.