Reputation: 415
I have a script with an optional verbosity argument. Depending on its value I want to suppress output (pushd in example below, but in reality other, mostly git commands). Example:
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
What I am looking for is something along:
push .. $cond # single line, outputing somehow controlled directly
popd $cond # ditto
Anybody can help? Thanks,
Hans-Peter
Upvotes: 0
Views: 352
Reputation: 44344
Use a different file descritor to redirect to:
if (( $verb ))
then
exec 3>&1
else
exec 3>/dev/null
fi
push .. >&3
popd >&3
This way, the condition is only tested once, at the beginning, rather then every time you do redirection.
Upvotes: 1
Reputation: 241768
You can redirect the output to a function whose definition depends on the $verb
:
#! /bin/bash
verb=$1
if [[ $verb ]] ; then
verb () {
cat
}
else
verb () {
: # Does nothing.
}
fi
echo A | verb
Upvotes: 2