2013-03-15 76 views
0

我有一个带有可选详细参数的脚本。根据它的值我想压制输出(在下面的例子中推,但实际上其他,主要是git命令)。例如:基于变量抑制输出

verb=1 
# pushd optionally outputs path (works but too long) 
if [ $verb ]; then 
    pushd .. 
else 
    pushd .. > /dev/null 
fi 
popd > /dev/null # the same if.. would be needed here 

我所寻找的东西沿着:

push .. $cond # single line, outputing somehow controlled directly 
popd $cond  # ditto 

任何人都可以帮忙吗?谢谢,

汉斯 - 彼得·

回答

1

使用不同的文件descritor重定向到:

if (($verb)) 
then 
    exec 3>&1 
else 
    exec 3>/dev/null 
fi 

push .. >&3 
popd >&3 

这样,条件仅在开始时测试一次,而不是在每次执行重定向时测试。

+0

非常优雅。现在查看I/O重定向,非常感谢! – 2013-03-15 12:37:35

2

可以输出重定向到其定义取决于$verb功能:

#! /bin/bash 

verb=$1 

if [[ $verb ]] ; then 
    verb() { 
     cat 
    } 
else 
    verb() { 
     :  # Does nothing. 
    } 
fi 

echo A | verb