Parameterize chained calls to a utility program in Bash
You could wrap it in a recursive function:
smooth() {
if [[ $1 -gt 1 ]]; then # add another call to function
command smooth | smooth $(($1 - 1))
else
command smooth # no further
fi
}
You would use this as
generate | smooth 5 | plot
which would be equivalent to
generate | smooth | smooth | smooth | smooth | smooth | plot
If you can afford to type as many commas as the amount of smooth
commands you want, you might take advantage of the shell's comma-separated Brace Expansion.
TL; DR
The whole command-line for your sample case would be:
generate | eval 'smooth |'{,,,,} plot
Note:
- add or remove commas if you want more or fewer repetitions of
smooth |
- there's no
|
beforeplot
because that's included in the lastsmooth |
string produced by the Brace Expansion - you can also provide arguments to
smooth
, as long as you can include them correctly within the quoted fixed part that precedes the open brace; in any case remember that you'd be providing them to all repetitions of the command
How it works
Comma-separated Brace Expansion allows you to dynamically produce strings, each made of a specified fixed part plus the specified variable parts. It produces as many strings as there are variable parts indicated, like a{b,c,d}
produces ab ac ad
.
The little trick here is that if you rather make a list of empty variable parts, i.e. with only commas inside the braces, the Brace Expansion will just produce copies of the fixed part only. For instance:
smooth{,,,,}
will produce:
smooth smooth smooth smooth smooth
Note that 4 commas produces 5 smooth
strings. That's just how this Brace Expansion works: it produces strings as many commas plus one.
Of course in your case you need also a |
separating each smooth
, so just add it in the fixed part but take care to quote it properly to have the shell not interpret it at once. That is:
'smooth|'{,,,,}
will produce:
'smooth|' 'smooth|' 'smooth|' 'smooth|' 'smooth|'
Take care of always placing the fixed part immediately adjacent to the open brace, i.e. no spaces between the '
and the {
.
(Note also that to form the fixed part you may also use double-quotes instead of single-quotes, if you need to expand shell variables in the fixed part. Just take care of the extra escaping that are required when some shell's special characters occur inside a double-quoted string).
At this point you need an eval
applied to that string in order to make the shell finally interpret it as the pipelined command it is supposed to be.
Thus, to sum it all, the whole command-line for your sample case would be:
generate | eval 'smooth |'{,,,,} plot