|
|
| UNIX Shell Programming, Revised Edition (ISBN: 067248448X) |
 |
List Price: $29.95
Our Price: $20.97
Used Price: $14.50
Release Date: 01 December, 1989
Manufacturer: Sams (Paperback)
Sales Rank: 2,838
Author: Stephen G. Kochan, Patrick H. Wood
|
More Info
|
|
|
Case
|
2002-09-03 22:50:38
|
| |
sh
|
|
|
|
|
Category: source:sh:general
|
|
Description: Parse arguments passed to your shellscript using case.
|
|
Platform: unix
|
|
Author: mind
|
|
Viewed: 2429
|
|
Rating: 4.6/5 (10 votes)
|
|
|
| If you have any questions about
this piece of code or still need help, try posting your question on the forum. |
#!/bin/sh
#
# case_sh - mind (mind@metalshell.com)
#
# Basic example on the case structure
#
# [ http://www.metalshell.com ]
# case word in [ pattern [ pattern ] ... ) list ;; ] esac
#
# word: would be a sequence of words or integers we are going to parse
# in: open's your case structure
# pattern: match this with the word we are parsing
# list: commands to perform if a pattern is found (;;) closes the pattern
# esac: closes our case structure
#
# case is a really good way to parse arguments passed to your program, something like
# what the example below shows.
print_usage()
{
echo "Usage: $0 <argument>"
echo " -h print this screen"
echo " -l print a list"
exit
}
print_list()
{
echo "This is our list"
echo " 1. first part"
echo " 2. second part"
echo " etc.."
exit
}
# start our first case structure
# Create a for structure to run through all the arguments passed to our script
# note: "$@" is equivalent to "$1" "$2", etc.. $1 would be our first argument and so on..
for arg in "$@"
do
# parse $arg
case $arg
in
# match each option with $arg if a match is found proccess the list
-h) print_usage;;
-l) print_list;;
# if an invalid option is given, print error and exit
*)
echo "Sorry but '$arg' is not a proper argument, please try -h";
exit;;
esac
done
|
|
|