在Bash中动态构建命令管道 [英] Dynamically building a command pipe in Bash
问题描述
我正在编写一个带有选项的bash程序。
I am writing a bash program that takes options.
例如: ./ my_program -l 3 -a -s
-
-l 3
将输出限制为三行 -
-a
将选择我的所有文件 -
-s
将对输出进行排序
-l 3
will limit the output to three lines-a
will select all my file-s
will sort the output
现在,我可以同时使用两种方法:
For now, I could use two options at a time this way:
if [ $all == 1 ]
then
if [ $sort == 1 ]
then
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//' | sort
else
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//'
fi
fi
如果使用 -a
选项,则打印整个文件;或者,如果使用 -a
选项和 -s
选项,我使用相同的命令,但是我使用 sort
。
If -a
option, I print the whole file, or, if -a
option and -s
option, I use the same command but i use sort
.
使用此解决方案,如果我要实现 -l </ code>,它将创建很多 if语句。
With this solution, if I want to implement the -l
, it would create a lot of "if" statements.
我首先想到的是创建一个包含命令的变量。
I first thought of creating a variable containing my command.
示例:
sort='sort'
limit='grep -m3'
然后以这种方式编写我的命令:
and then write my command this way:
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//' | $sort | $limit
但这根本行不通。
事实是,我想编写一个基本命令,并能够根据选项添加更多命令。
The fact is, I would like to write a basic command, and being able to add more to this one, depending of the options.
我该怎么办
推荐答案
一个棘手的,不太明显的解决方案,这是一个很好的问题。
Great question with a tricky, not-so-obvious solution.
您可以做的是将几个函数调用链接在一起。这些函数可以检查相关标志,然后执行某些操作,例如调用 sort
或不执行任何操作,然后仅调用 cat
。在管道中普通的 cat
调用本质上是无操作的:它将stdin不变地复制到stdout。
What you can do is chain together a couple of function calls. Those functions can examine the relevant flags and then either "do something" like call sort
or "do nothing" and simply call cat
. A plain cat
call in a pipeline is essentially a no-op: it copies stdin to stdout unchanged.
maybe_sort() {
if [[ $sort == 1 ]]; then
sort
else
cat
fi
}
maybe_limit() {
if [[ -n $limit ]]; then
head -n "$limit"
else
cat
fi
}
要使用这些,请输入:
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//' | maybe_sort | maybe_limit
这篇关于在Bash中动态构建命令管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!