shell OneLiner条件管道

wydwbb8l  于 2022-11-16  发布在  Shell
关注(0)|答案(2)|浏览(114)

问题

我想找到一种简单的单行方式,根据特定条件以管道方式传输字符串

次尝试

上面的代码是我尝试根据名为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

这显然行不通。

最终

如何在同一行中实现这一点?

gr8qqesn

gr8qqesn1#

您不能使管道本身具有条件,但可以包含if块作为管道的元素:

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

下面是一个更容易阅读的版本:

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

请注意,由于if块是管道的一部分,因此需要包含类似else cat子句的内容(正如我在上面所做的),以便无论if条件是否为真,something 都将传递管道数据。如果没有cat,它将被丢弃在隐喻的地板上。

os8fio9y

os8fio9y2#

条件执行如何?

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

相关问题