For example, I want to write a function called fooFun
, which will do some process on a PDF file. I'd like to make it able to run on both of the ways as following:
$ fooFun foo.pdf
$ ls *.pdf | fooFun
Any ideas? Thanks.
I don't think you can easily do this with a shell function. A better idea is to make it a script, let it take command line arguments, and achieve the second style with xargs
:
ls *.pdf | xargs fooFun
I agree with @larsmans, better to stick with passing arguments as parameters. However, here's how to achieve what you're asking:
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[@]}"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.