Bash/Scripting/Parse Args: Unterschied zwischen den Versionen

Aus SchnallIchNet
Wechseln zu: Navigation, Suche
Zeile 1: Zeile 1:
 +
==Parsen mit 'while'==
 
<pre>
 
<pre>
 
#!/bin/sh
 
#!/bin/sh
Zeile 31: Zeile 32:
 
</pre>
 
</pre>
  
test
+
==Parsen mit 'select'==
 +
<pre>
 +
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
 +
</pre>             
 +
 
 +
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...
  
 
=Siehe auch=
 
=Siehe auch=
 
[[Bash:Skeleton|Vorlage Bash-Script]]
 
[[Bash:Skeleton|Vorlage Bash-Script]]

Version vom 28. August 2009, 07:46 Uhr

Parsen mit 'while'

#!/bin/sh

while [ $1 ]; do
  case $1 in
      -u)
         shift;
         MYUSER=$1
         shift;
      ;;
      --quota)
         shift;
         Q=$1
         shift;
      ;;
      -h)
         echo "my help text "
      ;;
      *)
         echo "Unknown option $1"
         echo "Press enter to countinue"
         read dummy
      ;;
   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...

Siehe auch

Vorlage Bash-Script