sorin
sorin

Reputation: 170856

Conditional pipelining in 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

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)

Upvotes: 5

Views: 974

Answers (2)

Anubis
Anubis

Reputation: 7445

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.

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158280

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

Upvotes: 4

Related Questions