NodeX4
NodeX4

Reputation: 49

OneLiner conditonal pipe in bash

Problem

I want to find a simple, single line way to pipe a string depending on a certain condition

Attempt

The above code was my attempt at making a pipe conditional depending on a variable called textfolding.

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

This obviously did not work.

Final

How could I achieve this on the same one line?

Upvotes: 0

Views: 71

Answers (2)

seeker
seeker

Reputation: 864

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

Upvotes: 0

Gordon Davisson
Gordon Davisson

Reputation: 125818

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.

Upvotes: 3

Related Questions