例如,我想编写一个名为 的函数fooFun
,它将对 PDF 文件进行一些处理。我想让它能够以以下两种方式运行:
$ fooFun foo.pdf
$ ls *.pdf | fooFun
有任何想法吗?谢谢。
例如,我想编写一个名为 的函数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[@]}"
}