How to use a pipe in a script optionally

How can I achieve the conditional usage of a pipe for a command execution in a script.

It looks like this

#!/bin/bash
XCPRETTY=" | xcpretty"
if [ $(which xcpretty | wc -l) == 0 ]; then
    XCPRETTY=""
fi
xcodebuild archive ....... $XCPRETTY || exit 1

Solution 1:

Just use cat as a no-op if xcpretty is not installed:

XCPRETTY="xcpretty"
which xcpretty || XCPRETTY="cat"
xcodebuild archive ....... | eval $XCPRETTY || exit 1

Solution 2:

You could use the shell builtin eval to construct the command but your code becomes unclear. It would be much better to write your code as:

if  type xcpretty
then
    xcodebuild.... | xcpretty
else
    xcodebuild....
fi