繁体   English   中英

如何使Shell脚本函数能够在命令行中指定参数或从管道中获取参数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM