Bash中的条件流水线 [英] Conditional pipelining in Bash

查看:78
本文介绍了Bash中的条件流水线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要启用的过滤器,我想知道如何在bash中以一种干净的方式进行过滤.

I have a filter that I want to enable optionally and I wonder how can I do this in bash in a clean way.

FILTER="| sort" # also can be empty
ls $FILTER | cat

此代码不起作用,因为它将使用 | sort 作为参数调用 ls .

This code does not work because it will call ls with | and sort as parameters.

如何正确执行此操作?请注意,我试图避免创建 if 块,以使代码易于维护(我的管道链比此示例复杂得多)

How can I do this correctly? Please mind that I am trying to avoid creating if blocks in order to keep the code easy to maintain (my piping chain is considerable more complex than this example)

推荐答案

您要记住的内容不起作用,因为变量扩展发生在语法解析后 之后.

What you have in mind doesn't work because the variable expansion happens after the syntax has been parsed.

您可以执行以下操作:

foo_cmd | if [ "$order" = "desc" ] ; then
    sort -r
else
    sort
fi | if [ "$cut" = "on" ] ; then
    cut -f1
else
    cat
fi

这篇关于Bash中的条件流水线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆