首页 > 解决方案 > 对 exec 重定向到 /dev/null 感到困惑,我做得对吗?

问题描述

背景

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

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


问题

由于我很少使用exec手册页),我不确定我是否正确地执行以下想法?请详细说明。

如果脚本正在运行:


代码

# 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

    ...
}

标签: shellexecposixio-redirection

解决方案


看来我很接近了。由于该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
    ...
}

推荐阅读