Conditional pipelining in Bash

为君一笑 提交于 2021-02-07 18:12:41

问题


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

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

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)


回答1:


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

You can do something like this:

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



回答2:


You can create the command and execute it in a different shell.

FILTER="| sort" # create your filter here
# ls $FILTER | cat  <-- this won't work
bash -c "ls $FILTER | cat"

# or create the entire command and execute (which, i think, is more clean)
cmd="ls $FILTER | cat"
bash -c "$cmd"

If you select this approach, you must make sure the command is syntactically valid and does exactly what you intend, instead of doing something disastrous.



来源:https://stackoverflow.com/questions/45690174/conditional-pipelining-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!