Bash/Scripting/Parse Args: Unterschied zwischen den Versionen
Aus SchnallIchNet
Cbs (Diskussion | Beiträge) K (hat „Bash:Parse Args“ nach „Bash/Scripting/Parse Args“ verschoben) |
Cbs (Diskussion | Beiträge) |
||
Zeile 3: | Zeile 3: | ||
#!/bin/sh | #!/bin/sh | ||
− | while [ $1 ]; do | + | while [ "$1" ]; do |
− | + | optarg="" | |
− | + | opt="" | |
− | + | case "$1" in | |
− | + | -*=*) | |
− | + | opt=`echo "$1" | sed 's/=.*//'` | |
− | + | optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` | |
− | + | ;; | |
− | + | *) | |
− | + | opt=$1 | |
− | + | ;; | |
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
esac | esac | ||
+ | |||
+ | case $opt in | ||
+ | -u) | ||
+ | shift; # shift the '-u' | ||
+ | MYUSER=$1 | ||
+ | shift; # shift the val | ||
+ | ;; | ||
+ | |||
+ | --user) | ||
+ | MYUSER=$optarg; | ||
+ | shift; # shift the '--user=val' | ||
+ | ;; | ||
+ | |||
+ | -h|*) | ||
+ | echo "my help text " | ||
+ | exit 1 | ||
+ | ;; | ||
+ | esac | ||
done | done | ||
Zeile 50: | Zeile 59: | ||
=Siehe auch= | =Siehe auch= | ||
− | [[Bash | + | [[Bash/Scripting/Skeleton|Vorlage Bash-Script]] |
+ | [[Bash/Scripting/Variables|Gueligkeitsbereiche von Variablen]] |
Version vom 20. Juli 2010, 10:05 Uhr
Parsen mit 'while'
#!/bin/sh while [ "$1" ]; do optarg="" opt="" case "$1" in -*=*) opt=`echo "$1" | sed 's/=.*//'` optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; *) opt=$1 ;; esac case $opt in -u) shift; # shift the '-u' MYUSER=$1 shift; # shift the val ;; --user) MYUSER=$optarg; shift; # shift the '--user=val' ;; -h|*) echo "my help text " exit 1 ;; esac done echo "\$MYUSER = $MYUSER" echo "\$Q = $Q" exit 0
Parsen mit 'select'
select opt in $@; do if [ "$opt" = "Quit" ]; then echo done exit elif [ "$opt" = "Hello" ]; then echo Hello World else clear echo bad option fi done
If you run this script you'll see that it is a programmer's dream for text based menus. You'll probably notice that it's very similar to the 'for' construction, only rather than looping for each 'word' in $OPTIONS, it prompts the user. but use case construct in the select-loop instead...