2

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
    If something answered your question, can you mark it as the answer (click the checkmark)? Thanks. – jtbandes Oct 8 '09 at 0:51
11

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
  • 3
    Um, see what happens when you run script "arg with spaces". It may or may not be relevant to your situation. Once you're done, put doublequotes around $@ and $item. – wfaulk Oct 8 '09 at 0:15
  • Good point. Fixed. – jtbandes Oct 8 '09 at 0:27
3

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

2

"$@" does not solve his problem of "ANY number of arguments". there is a limit in how long a commandline can be (http://www.in-ulm.de/~mascheck/various/argmax/). 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

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