![](/img/trans.png)
[英]Writing a Shell Function that accepts input from a pipe and arguments simultaneously
[英]how to make a shell script function able to either specify arguments in command line or get them from a pipe?
例如,我想编写一个名为fooFun
的函数,它将对PDF文件进行一些处理。 我想使其能够在以下两种方式上运行:
$ fooFun foo.pdf
$ ls *.pdf | fooFun
有任何想法吗? 谢谢。
我不认为您可以使用shell函数轻松地做到这一点。 一个更好的主意是使它成为一个脚本,让它接受命令行参数,并使用xargs
实现第二种样式:
ls *.pdf | xargs fooFun
我同意@larsmans,最好坚持使用传递参数作为参数。 但是,以下是实现您所要求的方法:
foofun() {
local args arg
if [[ $# -eq 0 ]]; then
args=()
# consume stdin
while IFS= read -r arg; do args+=($arg); done
else
args=("$@")
fi
# do something with "${args[@]}"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.