1 |
frodo |
259 |
#!/bin/bash |
2 |
|
|
|
3 |
|
|
# A small example program for using the new getopt(1) program. |
4 |
|
|
# This program will only work with bash(1) |
5 |
|
|
# An similar program using the tcsh(1) script language can be found |
6 |
|
|
# as parse.tcsh |
7 |
|
|
|
8 |
|
|
# Example input and output (from the bash prompt): |
9 |
|
|
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long " |
10 |
|
|
# Option a |
11 |
|
|
# Option c, no argument |
12 |
|
|
# Option c, argument `more' |
13 |
|
|
# Option b, argument ` very long ' |
14 |
|
|
# Remaining arguments: |
15 |
|
|
# --> `par1' |
16 |
|
|
# --> `another arg' |
17 |
|
|
# --> `wow!*\?' |
18 |
|
|
|
19 |
|
|
# Note that we use `"$@"' to let each command-line parameter expand to a |
20 |
|
|
# separate word. The quotes around `$@' are essential! |
21 |
|
|
# We need TEMP as the `eval set --' would nuke the return value of getopt. |
22 |
|
|
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \ |
23 |
|
|
-n 'example.bash' -- "$@"` |
24 |
|
|
|
25 |
|
|
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi |
26 |
|
|
|
27 |
|
|
# Note the quotes around `$TEMP': they are essential! |
28 |
|
|
eval set -- "$TEMP" |
29 |
|
|
|
30 |
|
|
while true ; do |
31 |
|
|
case "$1" in |
32 |
|
|
-a|--a-long) echo "Option a" ; shift ;; |
33 |
|
|
-b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;; |
34 |
|
|
-c|--c-long) |
35 |
|
|
# c has an optional argument. As we are in quoted mode, |
36 |
|
|
# an empty parameter will be generated if its optional |
37 |
|
|
# argument is not found. |
38 |
|
|
case "$2" in |
39 |
|
|
"") echo "Option c, no argument"; shift 2 ;; |
40 |
|
|
*) echo "Option c, argument \`$2'" ; shift 2 ;; |
41 |
|
|
esac ;; |
42 |
|
|
--) shift ; break ;; |
43 |
|
|
*) echo "Internal error!" ; exit 1 ;; |
44 |
|
|
esac |
45 |
|
|
done |
46 |
|
|
echo "Remaining arguments:" |
47 |
|
|
for arg do echo '--> '"\`$arg'" ; done |