Options to arguments into scripts

Have you ever wondered how to get variables from a command line in a decent way?

Imagine you wrote a script that must check certain files how easy would it be to just enter the file on the command line interface as an option like this:

./yourscript.sh -f firstfile.txt
./yourscript.sh -f secondfile.txt

Here is some code to do just that. You will need to change the options according to your wishes.

#!/bin/sh

usage() {
echo "Usage: $0 -f FILE"
echo
echo " -f FILE"
echo "     Set the FILE variable."
exit 1
}

readargs() {
while [ "$#" -gt 0 ] ; do
  case "$1" in
   -f)
    if [ "$2" ] ; then
     file="$2"
     shift ; shift
    else
     echo "Missing a value for $1."
     echo
     shift
     usage
    fi
   ;;
   *)
    echo "Unknown option $1."
    echo
    shift
    usage
   ;;
  esac
done
}

readargs "$@"
if [ "$file" ] ; then
echo "You selected $file"
fi

Comments

I've used this process and it

I've used this process and it worked well. This is such a useful idea. - Fred Wehba

About Consultancy Articles Contact




References Red Hat Certified Architect By Robert de Bock Robert de Bock
Curriculum Vitae By Fred Clausen +31 6 14 39 58 72
By Nelson Manning [email protected]