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.txtHere 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