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



您将如何实现这一点?

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来关闭它

相关内容

  • 没有找到相关文章

最新更新