Utilizando case

*.Vamos a ver unos ejemplos.*

Sintaxis:

case expression in
    pattern1 )
        statements ;;
    pattern2 )
        statements ;;
    ...
esac

Ejemplo:

#! /bin/bash

if [ $# -lt 2 ]
then
        echo "Usage : $0 Signalnumber PID"
        exit
fi

case "$1" in

1)  echo "Sending SIGHUP signal"
    kill -SIGHUP $2
    ;;
2)  echo  "Sending SIGINT signal"
    kill -SIGINT $2
    ;;
3)  echo  "Sending SIGQUIT signal"
    kill -SIGQUIT $2
    ;;
9) echo  "Sending SIGKILL signal"
   kill -SIGKILL $2
   ;;
*) echo "Signal number $1 is not processed"
   ;;
esac

[rino@restauracion educacionit]$ ps -eaf |grep keepass
rino      1103  5663  0 15:22 pts/3    00:00:00 grep keepass
rino     27393     1  0 14:10 ?        00:00:03 keepass
[rino@restauracion educacionit]$

[rino@restauracion educacionit]$ ./signal.sh 9 27393
Sending SIGKILL signal
[rino@restauracion educacionit]$ 

En este ejemplo vemos que le  pasamos una señal y un numero de proceso y lo mata.

Otro Ejemplo:

#! /bin/bash
for filename in $(ls)
do
	# Take extension available in a filename
        ext=${filename##*\.}
        case "$ext" in
        c) echo "$filename : C source file"
           ;;
        o) echo "$filename : Object file"
           ;;
        sh) echo "$filename : Shell script"
            ;;
        txt) echo "$filename : Text file"
             ;;
        *) echo " $filename : Not processed"
           ;;
esac
done
$ ./filetype.sh
a.c : C source file
b.c : C source file
c1.txt : Text file
fileop.sh : Shell script
obj.o : Object file
text : Not processed
t.o : Object file

Uno mas.

#! /bin/bash

echo -n "Do you agree with this? [yes or no]: "
read yno
case $yno in

        [yY] | [yY][Ee][Ss] )
                echo "Agreed"
                ;;

        [nN] | [n|N][O|o] )
                echo "Not agreed, you can't proceed the installation";
                exit 1
                ;;
        *) echo "Invalid input"
            ;;
esac

$ ./yorno.sh
Do you agree with this? [yes or no]: YES
Agreed

Fuentes:http://www.thegeekstuff.com/2010/07/bash-case-statement/

Share
This entry was posted in Scripting and tagged . Bookmark the permalink.

Leave a Reply