问题
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