Home > database >  How to make a pipe conditional within the same line
How to make a pipe conditional within the same line

Time:05-09

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?

CodePudding user response:

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.

CodePudding user response:

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
  • Related