'How to make a pipe conditional within the same line

textfolding="ON"
echo "some text blah balh test foo" if [[ "$textfolding" == "ON" ]]; then | fold -s -w "$fold_width"  | sed -e "s|^|\t|g"; fi

The above code was my attempt of making a pipe conditional depending on a variable called textfolding. How could I achieve this on the same one line?



Solution 1:[1]

You can't make the pipe itself conditional, but you can include an if block as an element of the pipeline:

echo "some text blah balh test foo" | if [[ "$textfolding" == "ON" ]]; then fold -s -w "$fold_width" | sed -e "s|^|\t|g"; else cat; fi

Here's a more readable version:

echo "some text blah balh test foo" |
    if [[ "$textfolding" == "ON" ]]; then
        fold -s -w "$fold_width" | sed -e "s|^|\t|g"
    else
        cat
    fi

Note that since the if block is part of the pipeline, you need to include something like an else cat clause (as I did above) so that whether the if condition is true or not, something will pass the piped data through. Without the cat, it'd just get dropped on the metaphorical floor.

Solution 2:[2]

How about conditional execution?

textfolding="ON"
string="some text blah balh test foo"
[[ $textfolding == "ON" ]] && echo $string | fold -s -w $fold_width | sed -e "s|^|\t|g" || echo $string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gordon Davisson
Solution 2 seeker