通过Bash中的变量重定向STDOUT

Wax*_*Wax 3 bash stdout io-redirection

我想创建一个脚本,如果需要,可以在详细模式和静默模式下运行。我的想法是创建一个包含该变量的变量,"&> /dev/null"如果脚本以静默方式运行,则只需清除它即可。静默模式可以正常工作,但是如果我想将此作为最后的“参数”传递给某个东西(请参见我的示例),则它不起作用。

这是一个示例:我想要zip一些东西(我知道有一个-q选择,这个问题更像是理论上的问题),如果我编写此代码,它将按预期工作:

$ zip bar.zip foo
  adding: foo (stored 0%)
$ zip bar.zip foo &> /dev/null
$
Run Code Online (Sandbox Code Playgroud)

但是,当我声明&> /dev/null作为变量时,我得到了:

$ var="&> /dev/null"
$ zip bar.zip foo "$var"
zip warning: name not matched: &> /dev/null
updating: foo (stored 0%)
Run Code Online (Sandbox Code Playgroud)

我看到了其他解决方案,可以有意地重定向脚本的某些部分,但我很好奇我的想法是否可行,如果不能,为什么?在我的脚本中使用类似这样的命令会更方便,因为我只需要重定向一些行或命令,但是太多的话就不能用if

我正在尝试类似这样的事情:

if verbose
verbose="&> /dev/null"
else
verbose=

command1 $1 $2
command2 $1
command3 $1 $2 $3 "$verbose"
command4
Run Code Online (Sandbox Code Playgroud)

che*_*ner 5

bash/dev/stdout与重定向一起使用时,无论文件系统是否具有这样的条目,它将识别为标准输出的文件名。

# If an argument is given your script, use that value
# Otherwise, use /dev/stdout
out=${1:-/dev/stdout}

zip bar.zip foo > "$out"
Run Code Online (Sandbox Code Playgroud)