0

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.