SH条件redirect

我希望能够根据命令行开关将脚本的某些输出redirect/dev/null 。 我不知道该怎么做。

以一种愚蠢的方式,这将是这样的(以一种太简单的方式):

 #!/bin/sh REDIRECT= if [ $# -ge 1 -a "$1" = "--verbose" ]; then echo "Verbose mode." REDIRECT='1>&2 > /dev/null' fi echo "Things I want to see regardless of my verbose switch." #... Other things... # This command and others along the script should only be seen if I am in verbose mode. ls -l $REDIRECT 

任何线索,请?

感谢人们。

如果处于详细模式,则将STDOUT绑定到另一个句柄,否则将这些句柄链接到/ dev / null。 然后编写你的脚本,使可选的东西指向额外的句柄。

 #!/bin/sh exec 6>/dev/null if [ $# -ge 1 -a "$1" = "--verbose" ]; then echo "Verbose mode." exec 6>&1 fi echo "Things I want to see regardless of my verbose switch." #... Other things... # This command and others along the script should only be seen if I am in verbose mode. ls -l >&6 2>&1 

这应该让你开始。 我不确定这是否是BASH特定的。 这只是一个很久以前的记忆。 😉

我不知道sh但在bash (不一样!)你需要使用eval

 $ x='> foo' $ echo Hi $x Hi > foo $ eval echo Hi $x $ cat foo Hi 

我相信你的testing是倒退的。 使用详细模式时,您希望redirect到/dev/null

 if [ $# -ge 1 -a "$1" = "--verbose" ]; then echo "Verbose mode." else REDIRECT='2>&1 >/dev/null' fi