仅当未设置 VERBOSE 时才将输出重定向到 /dev/null

Redirect output to /dev/null only if VERBOSE is not set

你会如何完成这个?

if [[ -z $VERBOSE ]]; then
    REDIRECT=">/dev/null 2>/dev/null"
fi

echo "Installing Pip packages"  # Edited in for clarity
pip install requirements.txt $REDIRECT

echo "Installing other dependency"
<Install command goes here> $REDIRECT

您可以使用 exec:

重定向所有输出
if [[ -z $VERBOSE ]]; then
    exec >/dev/null 2>&1
fi

pip install requirements.txt

如果您想稍后在脚本中恢复输出,您可以复制文件描述符:

if [[ -z $VERBOSE ]]; then
    exec 3>&1
    exec 4>&2
    exec >/dev/null 2>&1
fi

# all the commands to redirect output for
pip install requirements.txt
# ...

# restore output
if [[ -z $VERBOSE ]]; then
    exec 1>&3
    exec 2>&4
fi

另一种选择是将文件描述符打开到 /dev/null 或复制描述符 1:

if [[ -z $VERBOSE ]]; then
    exec 3>/dev/null
else
    exec 3>&1
fi

echo "Installing Pip packages"
pip install requirements.txt >&3

exec 没有命令:

#!/usr/bin/env bash

if [[ ${VERBOSE:-0} -eq 0  ]]; then
   exec >/dev/null 2>/dev/null
fi

echo "Some text."

示例:

$ ./example.sh
$ VERBOSE=1 ./example.sh
Some text.
如果变量 name 未设置或设置为空字符串,则

${name:-word} 扩展为 word。这样你也可以VERBOSE=0关闭它。