【问题标题】:OneLiner conditonal pipe in bashbash 中的一个 Liner 条件管道
【发布时间】:2022-10-15 20:02:30
【问题描述】:
问题
我想找到一种简单的单行方式来根据特定条件对字符串进行管道传输
试图
上面的代码是我尝试根据名为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
这显然是行不通的。
最后
我怎么能在同一条线上实现这一目标?
【问题讨论】:
标签:
bash
shell
if-statement
pipe
script
【解决方案1】:
您不能使管道本身有条件,但您可以包含一个 if 块作为管道的一个元素:
echo "some text blah balh test foo" | if [[ "$textfolding" == "ON" ]]; then fold -s -w "$fold_width" | sed -e "s|^| |g"; else cat; fi
这是一个更易读的版本:
echo "some text blah balh test foo" |
if [[ "$textfolding" == "ON" ]]; then
fold -s -w "$fold_width" | sed -e "s|^| |g"
else
cat
fi
请注意,由于if 块是管道的一部分,因此您需要包含类似else cat 子句的内容(正如我在上面所做的那样),以便if 条件是否为真,某物将通过管道传递数据。如果没有cat,它只会掉在隐喻的地板上。
【解决方案2】:
条件执行怎么样?
textfolding="ON"
string="some text blah balh test foo"
[[ $textfolding == "ON" ]] && echo $string | fold -s -w $fold_width | sed -e "s|^| |g" || echo $string