M HYPE SPLASH
// updates

How to write a script to accept any number of command line arguments? (UNIX, BASH)

By John Peck

I have a script that I want to accept any number of command line arguments.

So far I have

if [ -O $1 ] ; then echo "you are the owner of $1"
else echo "you are not the owner of $1"
fi

Obviously if I wanted the script to only accept one argument this would work but what would work for ANY number of arguments.

ex. ./script f f1 f2 f3
1

3 Answers

One possible way to do what you want involves $@, which is an array of all the arguments passed in.

for item in "$@"; do if [ -O "$item" ]; then echo "you are the owner of $item" else echo "you are not the owner of $item" fi
done
2

Well, it depends on exactly what you want to do, but look into $*, $@, and shift.

"$@" does not solve his problem of "ANY number of arguments". there is a limit in how long a commandline can be (). a better way to read in "unlimited arguments" is via STDIN:

prg_which_creates_arguments | while read a; do \ echo "do something with $a"; \
done

just create the arguments and pipe them one after another at the code which is doing something with them.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy