├── .gitignore ├── LICENSE ├── README.md ├── chuleta-shell-script.odt ├── chuleta-shell-script.pdf ├── ejercicios-shell-script ├── ejercicios-shell-script.odt ├── ejercicios-shell-script.pdf └── solucion │ ├── 01-basicos │ ├── 01-hola-mundo.sh │ ├── 02-hola-parametros.sh │ ├── 03-hola-al-menos-1-parametro.sh │ ├── 04-hola-parametros-separados.sh │ ├── 05-hola-con-ayuda.sh │ ├── 06-hola-usuario.sh │ ├── 09-hola-usuario.sh │ ├── 11-hola-usuario.sh │ ├── usuarioconectado │ └── usuariosistema │ ├── 02-calculadora │ ├── calc01.sh │ ├── calc02.sh │ ├── calc03.sh │ ├── division │ ├── multiplica │ ├── notas.awk │ ├── notas.csv │ ├── notas.sh │ ├── resta │ └── suma │ ├── 03-banco │ ├── banco │ ├── banco-flags.sh │ └── banco-menu.sh │ ├── 04-demonios │ ├── alerta │ └── servicio-alerta.sh │ ├── 05-copias │ ├── copia-diferencial │ ├── copia-incremental │ ├── copia-total │ └── miCrontab │ └── 06-varios │ ├── arrays.sh │ ├── calendario │ ├── citas │ ├── citas-flags.sh │ ├── citas-menu.sh │ ├── elevado │ ├── jaula │ ├── ordena │ ├── quoting.sh │ ├── roles-con-awk.sh │ ├── roles-sin-awk.sh │ ├── roles.awk │ └── roles.csv └── git-push.sh /.gitignore: -------------------------------------------------------------------------------- 1 | documentacion 2 | e-books 3 | ejercicios-comandos-linux 4 | popurri 5 | recursos 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Adolfo Sanz De Diego 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Curso avanzado de Bash Shell Script 2 | =================================== 3 | 4 | Recursos: 5 | 6 | - [Chuleta de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/raw/master/chuleta-shell-script.pdf) [PDF] 7 | 8 | - [Chuleta de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/raw/master/chuleta-shell-script.odt) [ODT] 9 | 10 | - [Enunciado de los ejercicios de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/raw/master/ejercicios-shell-script/ejercicios-shell-script.pdf) [PDF] 11 | 12 | - [Enunciado de los ejercicios de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/raw/master/ejercicios-shell-script/ejercicios-shell-script.odt) [ODT] 13 | 14 | - [Solución de los ejercicios de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/tree/master/ejercicios-shell-script/solucion) 15 | 16 | - [Solución de los ejercicios de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/tree/master/ejercicios-shell-script/ejercicios-shell-script-solucion.pdf) [PDF] 17 | 18 | - [Solución de los ejercicios de Bash Shell Script](https://github.com/asanzdiego/curso-shell-script-2014/tree/master/ejercicios-shell-script/ejercicios-shell-script-solucion.odt) [ODT] 19 | -------------------------------------------------------------------------------- /chuleta-shell-script.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asanzdiego/curso-shell-script-2014/b8f835d32ec98950fb97e0e84874466ecff42945/chuleta-shell-script.odt -------------------------------------------------------------------------------- /chuleta-shell-script.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asanzdiego/curso-shell-script-2014/b8f835d32ec98950fb97e0e84874466ecff42945/chuleta-shell-script.pdf -------------------------------------------------------------------------------- /ejercicios-shell-script/ejercicios-shell-script.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asanzdiego/curso-shell-script-2014/b8f835d32ec98950fb97e0e84874466ecff42945/ejercicios-shell-script/ejercicios-shell-script.odt -------------------------------------------------------------------------------- /ejercicios-shell-script/ejercicios-shell-script.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asanzdiego/curso-shell-script-2014/b8f835d32ec98950fb97e0e84874466ecff42945/ejercicios-shell-script/ejercicios-shell-script.pdf -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/01-hola-mundo.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola mundo!" por pantalla 8 | 9 | echo "Hola mundo!" 10 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/02-hola-parametros.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | 9 | echo "Hola $*!" 10 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/03-hola-al-menos-1-parametro.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | # y que verifica que hayamos introducido al menos un parámetro 9 | 10 | echo "número de parámetros = $#" 11 | 12 | # si número de parámetros menor o igual que 0 13 | if [ $# -le 0 ]; then 14 | echo "Hay que introducir al menos un parámetro." 15 | exit 1 16 | fi 17 | 18 | echo "Hola $*!" 19 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/04-hola-parametros-separados.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | # separando cada parámetro con una coma (,) 9 | # y que verifica que hayamos introducido al menos un parámetro 10 | 11 | # si número de parámetros menor o igual que 0 12 | if [ $# -le 0 ]; then 13 | echo "Hay que introducir al menos un parámetro." 14 | exit 1 15 | fi 16 | 17 | MENSAJE="Hola" 18 | PRIMERO=1 19 | 20 | # iteramos sobre los parámetros 21 | for i in "$@"; do 22 | if [ $PRIMERO -eq 1 ]; then 23 | MENSAJE="$MENSAJE $i" 24 | PRIMERO=0 25 | else 26 | MENSAJE="$MENSAJE, $i" 27 | fi 28 | done 29 | 30 | # mostramos la salida por pantalla 31 | echo "$MENSAJE!" 32 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/05-hola-con-ayuda.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | # separando cada parámetro con una coma (,) 9 | # que verifica que hayamos introducido al menos un parámetro 10 | # y que muestra una ayuda en caso de error 11 | 12 | # función de ayuda 13 | function ayuda() { 14 | 15 | cat << DESCRPCION_AYUDA 16 | SYNOPSIS 17 | $0 NOMBRE_1 [NOMBRE_2] ... [NOMBRE_N] 18 | 19 | DESCRIPCION 20 | Muestra "Hola NOMBRE_1, NOMBRE_2, ... NOMBRE_N!" por pantalla. 21 | 22 | CÓDIGOS DE RETORNO 23 | 1 Si el número de parámetros es menor que 1 24 | 25 | DESCRPCION_AYUDA 26 | 27 | } 28 | 29 | # si número de parámetros <= 0 30 | if test $# -le 0 ; then 31 | echo "Hay que introducir al menos un parámetro." 32 | ayuda 33 | exit 1 34 | fi 35 | 36 | MENSAJE="Hola" 37 | PRIMERO=1 38 | 39 | # iteramos sobre los parámetros 40 | for i in "$@"; do 41 | if [ $PRIMERO -eq 1 ]; then 42 | MENSAJE="$MENSAJE $i" 43 | PRIMERO=0 44 | else 45 | MENSAJE="$MENSAJE, $i" 46 | fi 47 | done 48 | 49 | # mostramos la salida por pantalla 50 | echo "$MENSAJE!" 51 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/06-hola-usuario.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | # separando cada parámetro con una coma (,) 9 | # que verifica que hayamos introducido al menos un parámetro 10 | # que además verifique que sean usuarios conectados 11 | # y que muestra una ayuda en caso de error 12 | 13 | # función de ayuda 14 | function ayuda() { 15 | 16 | cat << DESCRPCION_AYUDA 17 | SYNOPSIS 18 | $0 NOMBRE_1 [NOMBRE_2] ... [NOMBRE_N] 19 | 20 | DESCRIPCION 21 | Muestra "Hola NOMBRE_1, NOMBRE_2, ... NOMBRE_N!" por pantalla. 22 | 23 | CÓDIGOS DE RETORNO 24 | 1 Si el número de parámetros es menor que 1 25 | 2 Si el usuario no está conectado 26 | DESCRPCION_AYUDA 27 | 28 | } 29 | 30 | # si número de parámetros <= 0 31 | if [ $# -le 0 ] ; then 32 | echo "Hay que introducir al menos un parámetro." 33 | ayuda 34 | exit 1 35 | fi 36 | 37 | MENSAJE="Hola" 38 | PRIMERO=1 39 | 40 | # iteramos sobre los parámetros 41 | for i in "$@"; do 42 | 43 | if [ "$(who | grep -E "^$i .+$" || echo "NO")" == "NO" ]; then 44 | echo "El usuario '$i' no está conectado" 45 | ayuda 46 | exit 2 47 | fi 48 | 49 | if [ $PRIMERO -eq 1 ]; then 50 | MENSAJE="$MENSAJE $i" 51 | PRIMERO=0 52 | else 53 | MENSAJE="$MENSAJE, $i" 54 | fi 55 | 56 | done 57 | 58 | # mostramos la salida por pantalla 59 | echo "$MENSAJE!" 60 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/09-hola-usuario.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | # separando cada parámetro con una coma (,) 9 | # que verifica que hayamos introducido al menos un parámetro 10 | # que además verifique que sean usuarios del sistema 11 | # y que muestra una ayuda en caso de error 12 | 13 | # función de ayuda 14 | function ayuda() { 15 | 16 | cat << DESCRPCION_AYUDA 17 | SYNOPSIS 18 | $0 NOMBRE_1 [NOMBRE_2] ... [NOMBRE_N] 19 | 20 | DESCRIPCION 21 | Muestra "Hola NOMBRE_1, NOMBRE_2, ... NOMBRE_N!" por pantalla. 22 | 23 | CÓDIGOS DE RETORNO 24 | 1 Si el número de parámetros es menor que 1 25 | 2 Si el usuario no está conectado 26 | DESCRPCION_AYUDA 27 | 28 | } 29 | 30 | # si número de parámetros <= 0 31 | if [ $# -le 0 ] ; then 32 | echo "Hay que introducir al menos un parámetro." 33 | ayuda 34 | exit 1 35 | fi 36 | 37 | MENSAJE="Hola" 38 | PRIMERO=1 39 | 40 | # iteramos sobre los parámetros 41 | for i in "$@"; do 42 | 43 | if [ "$(./usuarioconectado "$i")" == "NO" ]; then 44 | echo "El usuario '$i' no está conectado" 45 | ayuda 46 | exit 2 47 | fi 48 | 49 | if [ $PRIMERO -eq 1 ]; then 50 | MENSAJE="$MENSAJE $i" 51 | PRIMERO=0 52 | else 53 | MENSAJE="$MENSAJE, $i" 54 | fi 55 | 56 | done 57 | 58 | # mostramos la salida por pantalla 59 | echo "$MENSAJE!" 60 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/11-hola-usuario.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que saca un "Hola " + parámetros + "!" por pantalla 8 | # separando cada parámetro con una coma (,) 9 | # que verifica que hayamos introducido al menos un parámetro 10 | # que además verifique que sean usuarios del sistema 11 | # y que muestra una ayuda en caso de error 12 | 13 | # función de ayuda 14 | function ayuda() { 15 | 16 | cat << DESCRPCION_AYUDA 17 | SYNOPSIS 18 | $0 NOMBRE_1 [NOMBRE_2] ... [NOMBRE_N] 19 | 20 | DESCRIPCION 21 | Muestra "Hola NOMBRE_1, NOMBRE_2, ... NOMBRE_N!" por pantalla. 22 | 23 | CÓDIGOS DE RETORNO 24 | 1 Si el número de parámetros es menor que 1 25 | 2 Si el usuario no está en el sistema 26 | DESCRPCION_AYUDA 27 | 28 | } 29 | 30 | # si número de parámetros <= 0 31 | if [ $# -le 0 ] ; then 32 | echo "Hay que introducir al menos un parámetro." 33 | ayuda 34 | exit 1 35 | fi 36 | 37 | MENSAJE="Hola" 38 | PRIMERO=1 39 | 40 | # iteramos sobre los parámetros 41 | for i in "$@"; do 42 | 43 | if [ "$(./usuariosistema "$i")" == "NO" ]; then 44 | echo "El usuario '$i' no está en el sistema" 45 | ayuda 46 | exit 2 47 | fi 48 | 49 | if [ $PRIMERO -eq 1 ]; then 50 | MENSAJE="$MENSAJE $i" 51 | PRIMERO=0 52 | else 53 | MENSAJE="$MENSAJE, $i" 54 | fi 55 | 56 | done 57 | 58 | # mostramos la salida por pantalla 59 | echo "$MENSAJE!" 60 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/usuarioconectado: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que retorna 8 | # un SI si el primer parámetro coincide con algún usuario conectado 9 | # un NO en caso contrario 10 | 11 | function ayuda() { 12 | 13 | cat << DESCRIPCION_AYUDA 14 | SYNOPSIS 15 | $0 NOMBRE_USUARIO 16 | 17 | DESCRIPCION 18 | Devuelve: 19 | SI si NOMBRE_USUARIO coincide con algún usuario conectado o 20 | NO si NOMBRE_USUARIO no coincide con ningún usuario conectado 21 | 22 | CÓDIGOS DE RETORNO 23 | 1 Si el número de parámetros es distinto de 1 24 | DESCRIPCION_AYUDA 25 | 26 | } 27 | 28 | # si número de parámetros distinto 1 29 | if [ $# -ne 1 ]; then 30 | echo "El número de parámetros debe de igual a 1" 31 | ayuda 32 | exit 1 33 | fi 34 | 35 | who | grep -E "^$1 .+$" > /dev/null && echo "SI" || echo "NO" 36 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/01-basicos/usuariosistema: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que retorna 8 | # un SI si el primer parámetro coincide con algún usuario del sistema o 9 | # un NO en caso contrario 10 | 11 | function ayuda() { 12 | 13 | cat << DESCRIPCION_AYUDA 14 | SYNOPSIS 15 | $0 NOMBRE_USUARIO 16 | 17 | DESCRIPCION 18 | Devuelve: 19 | SI si NOMBRE_USUARIO coincide con algún usuario del sistema o 20 | NO si NOMBRE_USUARIO no coincide con ningún usuario del sistema 21 | 22 | CÓDIGOS DE RETORNO 23 | 1 Si el número de parámetros es distinto de 1 24 | DESCRIPCION_AYUDA 25 | 26 | } 27 | 28 | # si número de parámetros distinto 1 29 | if [ $# -ne 1 ]; then 30 | echo "El número de parámetros debe de igual a 1" 31 | ayuda 32 | exit 1 33 | fi 34 | 35 | grep -E "^$1:.+$" /etc/passwd > /dev/null && echo "SI" || echo "NO" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/calc01.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que realiza operaciones simples (suma resta multiplicacion división) 8 | # entre dos números 9 | 10 | # función de ayuda 11 | function ayuda() { 12 | 13 | cat << DESCRIPCION_AYUDA 14 | SYNOPSIS 15 | $0 NUMERO_1 OPERACIÓN NUMERO_2 16 | 17 | DESCRIPCIÓN 18 | Retorna el resultado de la OPERACIÓN 19 | entre NUMERO_1 y NUMERO_2 20 | 21 | OPERACIÓN puede tener estos valores: 22 | + sum mas 23 | - res menos 24 | x mul por 25 | / div entre 26 | 27 | CÓDIGOS DE RETORNO 28 | 1 Si el número de parámetros es distinto de 2. 29 | 2 Si algún parámetro no es un número. 30 | 3 Si la operación introducida es inválida. 31 | DESCRIPCION_AYUDA 32 | 33 | } 34 | 35 | function comprobarQueNoEsNumero() { 36 | 37 | if [ -n "$1" ] \ 38 | && [ "$1" != "0" ] \ 39 | && [ "$(echo "$1" | awk '{ print $1*1 }')" != "$1" ]; then 40 | 41 | echo "El parámetro '$1' no es un número" 42 | ayuda 43 | exit 2 44 | fi 45 | } 46 | 47 | # si número de parámetros distinto 3 48 | if [ $# -ne 3 ]; then 49 | echo "El número de parámetros debe de ser igual a 3" 50 | ayuda 51 | exit 1 52 | fi 53 | 54 | comprobarQueNoEsNumero "$1" 55 | comprobarQueNoEsNumero "$3" 56 | 57 | case $2 in 58 | +|sum|mas) ./suma "$1" "$3" ;; 59 | -|res|menos) ./resta "$1" "$3" ;; 60 | x|mul|por) ./multiplica "$1" "$3" ;; 61 | /|div|entre) ./division "$1" "$3" ;; 62 | *) echo "La operación '$2' es inválida." ; ayuda ; exit 3 ;; 63 | esac 64 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/calc02.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que realiza operaciones simples (suma resta multiplicacion división) 8 | # entre dos números 9 | 10 | # función de ayuda 11 | function ayuda() { 12 | 13 | cat << DESCRIPCION_AYUDA 14 | SYNOPSIS 15 | $0 NUMERO_1 OPERACIÓN NUMERO_2 16 | 17 | DESCRIPCIÓN 18 | Retorna el resultado de la OPERACIÓN 19 | entre NUMERO_1 y NUMERO_2 20 | 21 | OPERACIÓN puede tener estos valores: 22 | + sum mas 23 | - res menos 24 | x mul por 25 | / div entre 26 | 27 | CÓDIGOS DE RETORNO 28 | 1 Si el número de parámetros es distinto de 2. 29 | 2 Si algún parámetro no es un número. 30 | 3 Si la operación introducida es inválida. 31 | DESCRIPCION_AYUDA 32 | 33 | } 34 | 35 | function comprobarQueNoEsNumero() { 36 | 37 | if [ -n "$1" ] \ 38 | && [ "$1" != "0" ] \ 39 | && [ "$(echo "$1" | awk '{ print $1*1 }')" != "$1" ]; then 40 | 41 | echo "El parámetro '$1' no es un número" 42 | ayuda 43 | exit 2 44 | fi 45 | } 46 | 47 | if [ $# -ne 3 ]; then 48 | echo "El número de parámetros debe de ser igual a 3" 49 | ayuda 50 | exit 1 51 | fi 52 | 53 | comprobarQueNoEsNumero "$1" 54 | comprobarQueNoEsNumero "$3" 55 | 56 | case $2 in 57 | +|sum|mas) echo "$1" "$3" | awk '{ print $1 + $2 }' ;; 58 | -|res|menos) echo "$1" "$3" | awk '{ print $1 - $2 }' ;; 59 | x|mul|por) echo "$1" "$3" | awk '{ print $1 * $2 }' ;; 60 | /|div|entre) echo "$1" "$3" | awk '{ print $1 / $2 }' ;; 61 | *) echo "La operación '$2' es inválida." ; ayuda ; exit 3 ;; 62 | esac 63 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/calc03.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que devuelve el valor de la expresión introducida 8 | 9 | # función de ayuda 10 | function ayuda() { 11 | cat << DESCRIPCION_AYUDA 12 | SYNOPIS 13 | $0 EXPRESIÓN_NUMÉRICA 14 | 15 | DESCRIPCIÓN 16 | Muestra por pantalla el valor de EXPRESIÓN_NUMÉRICA. 17 | 18 | CODIGOS DE RETORNO 19 | 0 Si no hay ningún error. 20 | 1 Si el número de parámetros es distinto de 1. 21 | 2 Si hay un error de formato en la expresión introducida. 22 | 3 Si hay un error de entra y salida. 23 | 4 Si hay un error al ejecutar la expresión introducida. 24 | DESCRIPCION_AYUDA 25 | } 26 | 27 | # función de error 28 | # $1 línea de error 29 | # $2 mensaje de error 30 | # $3 código de retorno 31 | function error() { 32 | echo "$0: línea $1: Error $3: $2" 33 | exit "$3" 34 | } 35 | 36 | # si número de parámetros distinto 1 37 | if [ $# -ne 1 ] ; then 38 | error $LINENO "Hay que introducir 1 y solamente 1 parámetro." 1 39 | fi 40 | 41 | # si primer parámetro == '-h' o == '--help' 42 | if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then 43 | ayuda 44 | exit 0 45 | fi 46 | 47 | # si el parámetro no concuerda con la expresión regular 48 | if [ "$(echo "$1" | grep -E "^[\*\/0-9\(\)\+\-]+$")" == "" ]; then 49 | error $LINENO "Error de formato en la expresión introducida." 2 50 | fi 51 | 52 | # guardamos la expresión ($1) en el fichero oculto .expresion.awk 53 | # dentro de la HOME del usuario 54 | if ! echo "{ print $1 }" > ~/.expresion.awk 55 | then 56 | error $LINENO "Error de entrada y salida." 3 57 | fi 58 | 59 | # ejecutamos awk con el fichero oculto .expresion.awk 60 | if ! echo "" | awk -f ~/.expresion.awk 2> ~/.log.awk 61 | then 62 | error $LINENO "Error al ejecutar la expresión introducida." 4 63 | fi 64 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/division: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que divide dos números 8 | 9 | # función de ayuda 10 | function ayuda() { 11 | 12 | cat << DESCRPCION_AYUDA 13 | SYNOPSIS 14 | $0 NUMERO_1 NUMERO_2 15 | 16 | DESCRIPCION 17 | Retorna la división de NUMERO_1 y NUMERO_2 18 | 19 | CÓDIGOS DE RETORNO 20 | 1 Si el número de parámetros es distinto de 2 21 | 2 Si algún parámetro no es un número 22 | DESCRPCION_AYUDA 23 | 24 | } 25 | 26 | function comprobarQueNoEsNumero() { 27 | 28 | if [ -n "$1" ] \ 29 | && [ "$1" != "0" ] \ 30 | && [ "$(echo "$1" | awk '{ print $1*1 }')" != "$1" ]; then 31 | 32 | echo "El parámetro '$1' no es un número" 33 | ayuda 34 | exit 2 35 | fi 36 | } 37 | 38 | if [ $# -ne 2 ]; then 39 | echo "El número de parámetros debe de ser igual a 2" 40 | ayuda 41 | exit 1 42 | fi 43 | 44 | comprobarQueNoEsNumero "$1" 45 | comprobarQueNoEsNumero "$2" 46 | 47 | echo "$1" "$2" | awk '{ print $1 / $2 }' 48 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/multiplica: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que multiplica dos números 8 | 9 | # función de ayuda 10 | function ayuda() { 11 | 12 | cat << DESCRPCION_AYUDA 13 | SYNOPSIS 14 | $0 NUMERO_1 NUMERO_2 15 | 16 | DESCRIPCIÓN 17 | Retorna la multiplicación de NUMERO_1 y NUMERO_2 18 | 19 | CÓDIGOS DE RETORNO 20 | 1 Si el número de parámetros es distinto de 2 21 | 2 Si algún parámetro no es un número 22 | DESCRPCION_AYUDA 23 | 24 | } 25 | 26 | function comprobarQueNoEsNumero() { 27 | 28 | if [ -n "$1" ] \ 29 | && [ "$1" != "0" ] \ 30 | && [ "$(echo "$1" | awk '{ print $1*1 }')" != "$1" ]; then 31 | 32 | echo "El parámetro '$1' no es un número" 33 | ayuda 34 | exit 2 35 | fi 36 | } 37 | 38 | if [ $# -ne 2 ]; then 39 | echo "El número de parámetros debe de ser igual a 2" 40 | ayuda 41 | exit 1 42 | fi 43 | 44 | comprobarQueNoEsNumero "$1" 45 | comprobarQueNoEsNumero "$2" 46 | 47 | echo "$1" "$2" | awk '{ print $1 * $2 }' 48 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/notas.awk: -------------------------------------------------------------------------------- 1 | # esto se ejecutará solo una vez al principio 2 | BEGIN { 3 | 4 | print "+---------------------------+-----+------+" 5 | print "| NOMBRE EX1 EX2 EX3 | MED | APTO |" 6 | print "+---------------------------+-----+------+" 7 | } 8 | 9 | # esto se ejecutará para cada una de las líneas del fichero 10 | { 11 | suma2+=$2 12 | suma3+=$3 13 | suma4+=$4 14 | mediaFila=($2+$3+$4)/3 15 | 16 | apto="NO" 17 | if ( mediaFila >= 5 ) { 18 | apto="SI" 19 | aptos++ 20 | } 21 | 22 | print "| "$0" | "mediaFila" | "apto" |" 23 | } 24 | 25 | # esto se ejecutará solo una vez al final 26 | END { 27 | media2=suma2/3 28 | media3=suma3/3 29 | media4=suma4/3 30 | media=(media2+media3+media4)/3 31 | print "+---------------------------+-----+------+" 32 | print "| MEDIAS "media2" "media3" "media4" | "media" | "aptos" |" 33 | print "+---------------------------+-----+------+" 34 | } 35 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/notas.csv: -------------------------------------------------------------------------------- 1 | Pepito 3.1 4.4 5.7 2 | Fulanito 4.2 6.5 8.8 3 | Menganito 5.3 5.6 5.0 4 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/notas.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | awk -f notas.awk notas.csv 8 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/resta: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que resta dos números 8 | 9 | # función de ayuda 10 | function ayuda() { 11 | 12 | cat << DESCRPCION_AYUDA 13 | SYNOPSIS 14 | $0 NUMERO_1 NUMERO_2 15 | 16 | DESCRIPCIÓN 17 | Retorna la resta de NUMERO_1 y NUMERO_2 18 | 19 | CÓDIGOS DE RETORNO 20 | 1 Si el número de parámetros es distinto de 2 21 | 2 Si algún parámetro no es un número 22 | DESCRPCION_AYUDA 23 | 24 | } 25 | 26 | function comprobarQueNoEsNumero() { 27 | 28 | if [ -n "$1" ] \ 29 | && [ "$1" != "0" ] \ 30 | && [ "$(echo "$1" | awk '{ print $1*1 }')" != "$1" ]; then 31 | 32 | echo "El parámetro '$1' no es un número" 33 | ayuda 34 | exit 2 35 | fi 36 | } 37 | 38 | if [ $# -ne 2 ]; then 39 | echo "El número de parámetros debe de ser igual a 2" 40 | ayuda 41 | exit 1 42 | fi 43 | 44 | comprobarQueNoEsNumero "$1" 45 | comprobarQueNoEsNumero "$2" 46 | 47 | echo "$1" "$2" | awk '{ print $1 - $2 }' 48 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/02-calculadora/suma: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que suma dos números 8 | 9 | # función de ayuda 10 | function ayuda() { 11 | 12 | cat << DESCRPCION_AYUDA 13 | SYNOPSIS 14 | $0 NUMERO_1 NUMERO_2 15 | 16 | DESCRIPCIóN 17 | Retorna la suma de NUMERO_1 y NUMERO_2 18 | 19 | CÓDIGOS DE RETORNO 20 | 1 Si el número de parámetros es distinto de 2 21 | 2 Si algún parámetro no es un número 22 | DESCRPCION_AYUDA 23 | 24 | } 25 | 26 | function comprobarQueNoEsNumero() { 27 | 28 | if [ -n "$1" ] \ 29 | && [ "$1" != "0" ] \ 30 | && [ "$(echo "$1" | awk '{ print $1*1 }')" != "$1" ]; then 31 | 32 | echo "El parámetro '$1' no es un número" 33 | ayuda 34 | exit 2 35 | fi 36 | } 37 | 38 | if [ $# -ne 2 ]; then 39 | echo "El número de parámetros debe de ser igual a 2" 40 | ayuda 41 | exit 1 42 | fi 43 | 44 | comprobarQueNoEsNumero "$1" 45 | comprobarQueNoEsNumero "$2" 46 | 47 | echo "$1" "$2" | awk '{ print $1 + $2 }' 48 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/03-banco/banco: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | BANCO_FILE="$HOME/.banco.txt" 8 | 9 | function help() { 10 | 11 | cat << DESCRIPCION_AYUDA 12 | SYNOPSIS 13 | $0 OPCION [PARAMETRO_2] ... [PARAMETRO_N] 14 | 15 | DESCRIPCIÓN 16 | Añade, busca, lista y opera con movimientos bancarios. 17 | 18 | OPCIONES 19 | -h --help Muestra una ayuda. 20 | -a --add FECHA CONCEPTO CANTIDAD Añade un movimiento bancario. 21 | -s --search PATRÓN Busca un movimiento bancario. 22 | -l --list Lista los movimientos bancarios ordenados por fecha. 23 | -t --total Calcula el saldo total de la cuenta. 24 | 25 | CÓDIGOS DE RETORNO 26 | 0 Si no hay ningún error. 27 | 1 SI la opción introducida no es válida. 28 | 2 si un argumento númerico no es un número. 29 | 3 Si el número de parámetros es erróneo. 30 | 4 si un argumento de tipo fecha no es una fecha. 31 | 5 Si hay un error de entrada/salida en $BANCO_FILE. 32 | DESCRIPCION_AYUDA 33 | 34 | } 35 | 36 | function exitWithError() { 37 | 38 | LINEA_ERROR="$1" 39 | MENSAJE_ERROR="$2" 40 | CODIGO_ERROR="$3" 41 | 42 | echo "$0: línea $LINEA_ERROR: Error $CODIGO_ERROR: $MENSAJE_ERROR" 43 | exit "$CODIGO_ERROR" 44 | } 45 | 46 | function testDateExists() { 47 | 48 | DATE="$1" 49 | 50 | # si ya existe un movimiento bancario para la misma fecha 51 | if [ "$(grep -E "^$DATE" "$BANCO_FILE")" != "" ]; then 52 | exitWithError $LINENO "Ya existe un movimiento bancario para la fecha '$DATE'." 12 53 | fi 54 | } 55 | 56 | function testIsDate() { 57 | 58 | DATE="$1" 59 | 60 | if [ "$(echo "$DATE" | grep -E "^20[0-9]{2}-[01][0-9]-[0-3][0-9]$")" == "" ]; then 61 | exitWithError $LINENO "'$DATE' no es una fecha" 4 62 | fi 63 | } 64 | 65 | function testIsNumber() { 66 | 67 | NUMBER="$1" 68 | 69 | if [ -n "$NUMBER" ] \ 70 | && [ "$NUMBER" != "0" ] \ 71 | && [ "$(echo "$NUMBER" | awk '{ print $1*1 }')" != "$NUMBER" ]; then 72 | 73 | exitWithError $LINENO "'$NUMBER' no es un número" 2 74 | fi 75 | } 76 | 77 | function testParameterNumer() { 78 | 79 | PARAMETER_NUMBER="$1" 80 | shift 81 | if [ $# -ne "$PARAMETER_NUMBER" ]; then 82 | exitWithError $LINENO \ 83 | "Número de parámetros obligatorio: $PARAMETER_NUMBER" 3 84 | fi 85 | } 86 | 87 | function add() { 88 | echo "$@" 89 | testParameterNumer 3 "$@" 90 | 91 | FECHA="$1" 92 | CONCEPTO="$2" 93 | CANTIDAD="$3" 94 | 95 | testIsDate "$FECHA" 96 | testDateExists "$FECHA" 97 | testIsNumber "$CANTIDAD" 98 | 99 | echo "$FECHA $CONCEPTO $CANTIDAD" >> "$BANCO_FILE" 100 | } 101 | 102 | function search() { 103 | 104 | testParameterNumer 1 "$@" 105 | 106 | PATRON="$1" 107 | 108 | grep "$PATRON" "$BANCO_FILE" 109 | } 110 | 111 | # lista movimientos ordenados por fecha 112 | function list() { 113 | 114 | sort -nk 1 "$BANCO_FILE" 115 | } 116 | 117 | function total() { 118 | 119 | awk '{s+=$3} END {print "Total="s}' "$BANCO_FILE" 120 | } 121 | 122 | function createFileIfNotExists() { 123 | 124 | if ! touch "$BANCO_FILE"; then 125 | exitWithError $LINENO \ 126 | "Error de entrada/salida en el fichero $BANCO_FILE" 5 127 | fi 128 | } 129 | 130 | function menu() { 131 | 132 | if [ $# -lt 1 ]; then 133 | exitWithError $LINENO \ 134 | "Mínimo número de parámetros: 1" 3 135 | fi 136 | 137 | case $1 in 138 | -h|--help) help;; 139 | -a|--add) shift; add "$@";; 140 | -s|--search) shift; search "$@";; 141 | -l|--list) list;; 142 | -t|--total) total;; 143 | *) exitWithError $LINENO "Opción '$1' inválida." 1 144 | esac 145 | } 146 | 147 | function init() { 148 | 149 | createFileIfNotExists 150 | menu "$@" 151 | } 152 | 153 | init "$@" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/03-banco/banco-flags.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que añade, busca y opera con movimientos bancarios. 8 | 9 | # variables globales 10 | BANCO_SCRIPT=./banco 11 | 12 | # función de ayuda 13 | function help() { 14 | cat << DESCRIPCION_AYUDA 15 | SYNOPIS 16 | $0 [OPCIÓN] [PARÁMETROS] 17 | 18 | DESCRIPCIÓN 19 | Añade, busca, lista y opera con movimientos bancarios. 20 | 21 | OPCIONES 22 | -h --help Muestra una ayuda. 23 | -a --add FECHA CONCEPTO CANTIDAD Añade un movimiento bancario. 24 | -s --search PATRÓN Busca un movimiento bancario. 25 | -l --list Lista los movimientos bancarios ordenados por fecha. 26 | -t --total Calcula el saldo total de la cuenta. 27 | 28 | CÓDIGOS DE RETORNO 29 | 0 Si no hay ningún error. 30 | 1 Si la opción introducida no es válida. 31 | 2 Si un argumento númerico no es un número. 32 | 3 Si el número de parámetros es erróneo. 33 | 4 Si un argumento de tipo fecha no es una fecha. 34 | 5 Si hay un error de entrada/salida en el fichero de datos. 35 | 6 Si no introducen ningún parámetro. 36 | DESCRIPCION_AYUDA 37 | } 38 | 39 | # función para añadir un movimiento bancario 40 | function add() { 41 | echo "AÑADIR UN MOVIMIENTO BANCARIO" 42 | $BANCO_SCRIPT --add "$@" 43 | echo "-----------------------------" 44 | } 45 | 46 | # función para búscar un movimiento bancario 47 | function search() { 48 | echo "BUSCAR MOVIMIENTO BANCARIO ($*)" 49 | $BANCO_SCRIPT --search "$@" 50 | echo "-----------------------------" 51 | } 52 | 53 | # función para listar movimientos bancarios ordenados por mes y día 54 | function list() { 55 | echo "LISTAR ORDENADO POR FECHA" 56 | $BANCO_SCRIPT --list 57 | echo "-----------------------------" 58 | } 59 | 60 | # función para mostrar el saldo total de la cuenta 61 | function total() { 62 | echo "SALDO TOTAL DE LA CUENTA" 63 | $BANCO_SCRIPT --total 64 | echo "-----------------------------" 65 | } 66 | 67 | # función opción invalida 68 | function opcion_invalida() { 69 | echo "Opción '$1' inválida." 70 | exit 6 71 | } 72 | 73 | # si número de parámetros menor o igual que 0 74 | if [ $# -le 0 ]; then 75 | echo "Hay que introducir al menos un parámetro." 76 | help 77 | exit 6 78 | fi 79 | 80 | case $1 in 81 | -h|--help) help;; 82 | -a|--add) shift; add "$@";; 83 | -s|--search) shift; search "$@";; 84 | -l|--list) list;; 85 | -t|--total) total;; 86 | *) exitWithError $LINENO "Opción '$1' inválida." 1 87 | esac 88 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/03-banco/banco-menu.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que añade, busca y opera con movimientos bancarios. 8 | 9 | # variables globales 10 | BANCO_SCRIPT=./banco 11 | 12 | # función de ayuda 13 | function ayuda() { 14 | cat << DESCRIPCION_AYUDA 15 | SYNOPIS 16 | $0 [OPCIONES] 17 | 18 | DESCRIPCIÓN 19 | Añade y busca y opera con movimientos bancarios. 20 | 21 | OPCIONES 22 | -h --help Muesta esta ayuda. 23 | 24 | CODIGOS DE RETORNO 25 | 0 Si no hay ningún error. 26 | DESCRIPCION_AYUDA 27 | } 28 | 29 | # función menu 30 | function menu() { 31 | cat << DESCRIPCION_MENU 32 | 33 | +-----------------------------------------------------------------+ 34 | | MENU DEL BANCO | 35 | +-----------------------------------------------------------------+ 36 | | a - Añadir un movimiento bancario. | 37 | | b - Buscar un movimiento bancario. | 38 | | l - Listar todos los movimientos bancarios ordenados por fecha. | 39 | | t - Calcular el saldo total de la cuenta. | 40 | | s - Salir del programa. | 41 | +-----------------------------------------------------------------+ 42 | 43 | DESCRIPCION_MENU 44 | } 45 | 46 | # función de error 47 | # $1 línea de error 48 | # $2 mensaje de error 49 | function error() { 50 | echo "$0: línea $1: $2" 51 | } 52 | 53 | # función para añadir un movimiento bancario 54 | function add() { 55 | echo "AÑADIR UN MOVIMIENTO BANCARIO" 56 | read -r -p "Introduce el fecha: " FECHA 57 | read -r -p "Introduce el concepto: " CONCEPTO 58 | read -r -p "Introduce la cantidad: " CANTIDAD 59 | $BANCO_SCRIPT --add "$FECHA" "$CONCEPTO" "$CANTIDAD" 60 | elegir_menu 61 | } 62 | 63 | # función para búscar un movimiento bancario 64 | function search() { 65 | echo "BUSCAR MOVIMIENTO BANCARIO" 66 | read -r -p "Introduce un patrón de búsqueda: " PATRON 67 | $BANCO_SCRIPT --search "$PATRON" 68 | elegir_menu 69 | } 70 | 71 | # función para listar movimientos bancarios ordenados por mes y día 72 | function list() { 73 | echo "LISTAR ORDENADO POR FECHA" 74 | $BANCO_SCRIPT --list 75 | elegir_menu 76 | } 77 | 78 | # función para mostrar el saldo total de la cuenta 79 | function total() { 80 | echo "SALDO TOTAL DE LA CUENTA" 81 | $BANCO_SCRIPT --total 82 | elegir_menu 83 | } 84 | 85 | # función para salir del programa 86 | function salir() { 87 | exit 0 88 | } 89 | 90 | # función opción invalida 91 | function opcion_invalida() { 92 | echo "Opción '$1' inválida." 93 | elegir_menu 94 | } 95 | 96 | # función elegir_menu 97 | function elegir_menu() { 98 | 99 | menu 100 | read -r -p "Elige una opción: " OPCION 101 | clear 102 | 103 | case "$OPCION" in 104 | a) add ;; 105 | b) search ;; 106 | l) list ;; 107 | t) total ;; 108 | s) salir ;; 109 | *) opcion_invalida "$OPCION";; 110 | esac 111 | } 112 | 113 | parametros() { 114 | # si primer parámetro == '-h' o == '--help' 115 | if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then 116 | ayuda 117 | exit 0 118 | fi 119 | } 120 | 121 | if [ $# -gt 0 ]; then 122 | parametros "$1" 123 | fi 124 | 125 | clear 126 | 127 | elegir_menu 128 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/04-demonios/alerta: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que escribe la fecha en formato 'dd/mm/aaaa hh:mm:ss' cada X segundos 8 | # en el log '~/alerta.log' 9 | 10 | # función de ayuda 11 | function ayuda() { 12 | cat << DESCRIPCION_AYUDA 13 | SYNOPIS 14 | $0 [SEGUNDOS] 15 | 16 | DESCRIPCION 17 | Escribe la fecha cada X segundos en el log '~/alerta.log' 18 | 19 | CODIGOS DE RETORNO 20 | 0 Si no hay ningún error 21 | DESCRIPCION_AYUDA 22 | } 23 | 24 | DEFAULT=2 25 | SEGUNDOS=$DEFAULT 26 | 27 | if [ "$#" -gt 0 ]; then 28 | 29 | # si primer parámetro == '-h' o == '--help' 30 | if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then 31 | ayuda 32 | exit 0 33 | fi 34 | 35 | SEGUNDOS=$1 36 | fi 37 | 38 | 39 | function main() { 40 | 41 | # comprobar que SEGUNDOS es un número 42 | if [ "$SEGUNDOS" != "0" ] && [ "$(echo "$SEGUNDOS" | awk '{ print $1 * 1 }')" != "$SEGUNDOS" ]; then 43 | echo "El parámetro '$1' no es un número. Se cogerá el valor por defecto ($DEFAULT)" 44 | SEGUNDOS=$DEFAULT 45 | fi 46 | 47 | # reinicio alerta.log 48 | echo "" > ~/alerta.log 49 | 50 | while true; do 51 | date +%d/%m/%Y" "%H:%M:%S >> ~/alerta.log 52 | sleep $SEGUNDOS 53 | done 54 | } 55 | 56 | echo "$$" 57 | 58 | main "$@" 59 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/04-demonios/servicio-alerta.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que arraca, para, relanza y nos muestra el estado de 'alerta' 8 | 9 | # función de ayuda 10 | function ayuda() { 11 | cat << DESCRIPCION_AYUDA 12 | SYNOPIS 13 | $0 start|stop|restart|status 14 | 15 | DESCRIPCIÓN 16 | Muestra que arraca, para, relanza y nos muestra el estado de 'alerta'. 17 | 18 | CÓDIGOS DE RETORNO 19 | 0 Si no hay ningún error. 20 | DESCRIPCION_AYUDA 21 | } 22 | 23 | DAEMON=alerta 24 | PIDFILE=/tmp/$DAEMON.pid 25 | 26 | # función que arranca 'alerta' 27 | function do_start() { 28 | 29 | # si exite el fichero 30 | if [ -e $PIDFILE ]; then 31 | echo "El proceso ya se está ejecutando." 32 | exit 0; 33 | fi 34 | ./$DAEMON & 35 | echo $! > $PIDFILE 36 | echo "Ejecutandose..." 37 | } 38 | 39 | # función que para 'alerta' 40 | function do_stop() { 41 | 42 | # si exite el fichero 43 | if [ -e $PIDFILE ]; then 44 | kill -9 "$(cat $PIDFILE)" 45 | rm $PIDFILE 46 | fi 47 | echo "Parado." 48 | } 49 | 50 | # función que para y arrance 'alerta' 51 | function do_restart() { 52 | 53 | do_stop 54 | do_start 55 | } 56 | 57 | # función que muestra el estado de 'alerta' 58 | function do_status() { 59 | 60 | # si exite el fichero 61 | if [ -e $PIDFILE ]; then 62 | echo "Ejecutandose..." 63 | else 64 | echo "Parado." 65 | fi 66 | } 67 | 68 | # si número de parámetros distinto 3 69 | if [ $# -ne 1 ]; then 70 | echo "El número de parámetros debe de ser igual a 1" 71 | ayuda 72 | exit 1 73 | fi 74 | 75 | case $1 in 76 | -h|--help) 77 | ayuda ;; 78 | start) 79 | do_start ;; 80 | stop) 81 | do_stop ;; 82 | restart) 83 | do_restart ;; 84 | status) 85 | do_status ;; 86 | *) 87 | echo "Parámetro '$1' incorrecto." ;; 88 | esac 89 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/05-copias/copia-diferencial: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que empaqueta y comprime los ficheros modificados 8 | # desde la última copia-total 9 | # en un fichero llamado diferencial-aaaa.mm.dd-HH.MM.SS.tar.zip 10 | 11 | ############################################################ 12 | # INICIO VARIABLES 13 | ############################################################ 14 | 15 | # variable con la fecha en el formato indicado (aaaa.mm.dd-HH.MM.SS) 16 | FECHA="$(date +%Y.%m.%d-%H.%M.%S)" 17 | 18 | # variable con la ruta de los ficheros 19 | RUTA_FICHEROS="$HOME/copia_seguridad" 20 | 21 | # variable con el fichero con la fecha de la última copia total 22 | FICHERO_ULTIMA_COPIA_TOTAL="$RUTA_FICHEROS/fecha-ultima-copia-total.txt" 23 | 24 | # variable con el fichero con la fecha de la última copia diferencial 25 | FICHERO_ULTIMA_COPIA_DIFERENCIAL="$RUTA_FICHEROS/fecha-ultima-copia-diferencial.txt" 26 | 27 | # variable con el fichero comprimido 28 | FICHERO_COMPRIMIDO="$RUTA_FICHEROS/diferencial-$FECHA.tar.zip" 29 | 30 | # variable con eldirectorio que queremos copiar y comprimir 31 | DIRECTORIO_A_COPIAR="$HOME/directorio_a_copiar" 32 | 33 | ############################################################ 34 | # FIN VARIABLES 35 | ############################################################ 36 | 37 | # si no exixte el directorio a copiar mostramos un error y paramos la ejecución 38 | if [ ! -d "$DIRECTORIO_A_COPIAR" ]; then 39 | echo "No exixte el directorio a copiar." 40 | exit 1 41 | fi 42 | 43 | # si no existe el FICHERO_ULTIMA_COPIA_TOTAL mostramos un error 44 | # y paramos la ejecución 45 | if [ ! -e "$FICHERO_ULTIMA_COPIA_TOTAL" ]; then 46 | echo "No hay última copia total." 47 | exit 1 48 | fi 49 | 50 | # si no exixte el directorio de los ficheros lo creamos 51 | if [ ! -d "$RUTA_FICHEROS" ]; then 52 | mkdirs "$RUTA_FICHEROS" 53 | fi 54 | 55 | # empaquetamos y comprimimos los ficheros modificados 56 | # desde la última copia total 57 | find "$DIRECTORIO_A_COPIAR"/* -newer "$FICHERO_ULTIMA_COPIA_TOTAL" | zip -@ "$FICHERO_COMPRIMIDO" 58 | 59 | # guardar la fecha de la última copia diferencial 60 | # en FICHERO_ULTIMA_COPIA_DIFERENCIAL 61 | echo "$FECHA" > "$FICHERO_ULTIMA_COPIA_DIFERENCIAL" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/05-copias/copia-incremental: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script que empaqueta y comprime los ficheros modificados 8 | # desde la última copia incremental 9 | # en un fichero llamado incremental-aaaa.mm.dd-HH.MM.SS.tar.zip 10 | 11 | ############################################################ 12 | # INICIO VARIABLES 13 | ############################################################ 14 | 15 | # variable con la fecha en el formato indicado (aaaa.mm.dd-HH.MM.SS) 16 | FECHA="$(date +%Y.%m.%d-%H.%M.%S)" 17 | 18 | # variable con la ruta de los ficheros 19 | RUTA_FICHEROS="$HOME/copia_seguridad" 20 | 21 | # variable con el fichero con la fecha de la última copia total 22 | FICHERO_ULTIMA_COPIA_TOTAL="$RUTA_FICHEROS/fecha-ultima-copia-total.txt" 23 | 24 | # variable con el fichero con la fecha de la última copia incremental 25 | FICHERO_ULTIMA_COPIA_INCREMENTAL="$RUTA_FICHEROS/fecha-ultima-copia-incremental.txt" 26 | 27 | # variable con el fichero comprimido 28 | FICHERO_COMPRIMIDO="$RUTA_FICHEROS/incremental-$FECHA.tar.zip" 29 | 30 | # variable con eldirectorio que queremos copiar y comprimir 31 | DIRECTORIO_A_COPIAR="$HOME/directorio_a_copiar" 32 | 33 | ############################################################ 34 | # FIN VARIABLES 35 | ############################################################ 36 | 37 | # si no exixte el directorio a copiar mostramos un error 38 | # y paramos la ejecución 39 | if [ ! -d "$DIRECTORIO_A_COPIAR" ]; then 40 | echo "No exixte el directorio a copiar." 41 | exit 1 42 | fi 43 | 44 | # si no existe el FICHERO_ULTIMA_COPIA_INCREMENTAL 45 | # vemos si existe el fichero FICHERO_ULTIMA_COPIA_TOTAL 46 | # si no existe ninguno mostramos un error 47 | # y paramos la ejecución 48 | if [ ! -e "$FICHERO_ULTIMA_COPIA_INCREMENTAL" ]; then 49 | if [ ! -e "$FICHERO_ULTIMA_COPIA_TOTAL" ]; then 50 | echo "No hay última copia incremental ni total." 51 | exit 1 52 | else 53 | FICHERO_FLAG=$FICHERO_ULTIMA_COPIA_TOTAL 54 | fi 55 | else 56 | FICHERO_FLAG=$FICHERO_ULTIMA_COPIA_INCREMENTAL 57 | fi 58 | 59 | # si no exixte el directorio de los ficheros lo creamos 60 | if [ ! -d "$RUTA_FICHEROS" ]; then 61 | mkdirs "$RUTA_FICHEROS" 62 | fi 63 | 64 | # empaqueta y comprime los ficheros modificados 65 | # desde la última copia incremental 66 | find "$DIRECTORIO_A_COPIAR"/* -newer "$FICHERO_FLAG" | zip -@ "$FICHERO_COMPRIMIDO" 67 | 68 | # guardar la fecha de la última copia incremental 69 | # en FICHERO_ULTIMA_COPIA_INCREMENTAL 70 | echo "$FECHA" > "$FICHERO_ULTIMA_COPIA_INCREMENTAL" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/05-copias/copia-total: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | ############################################################ 8 | # INICIO VARIABLES 9 | ############################################################ 10 | 11 | # variable con la fecha en el formato indicado (aaaa.mm.dd-HH.MM.SS) 12 | FECHA="$(date +%Y.%m.%d-%H.%M.%S)" 13 | 14 | # variable con la ruta de los ficheros 15 | RUTA_FICHEROS="$HOME/copia_seguridad" 16 | 17 | # variable con el fichero con la fecha de la última copia total 18 | FICHERO_ULTIMA_COPIA_TOTAL="$RUTA_FICHEROS/fecha-ultima-copia-total.txt" 19 | 20 | # variable con el fichero comprimido 21 | FICHERO_COMPRIMIDO="$RUTA_FICHEROS/total-$FECHA.tar.zip" 22 | 23 | # variable con el directorio que queremos copiar y comprimir 24 | DIRECTORIO_A_COPIAR="$HOME/directorio_a_copiar" 25 | 26 | ############################################################ 27 | # FIN VARIABLES 28 | ############################################################ 29 | 30 | # si no exixte el directorio a copiar mostramos un error 31 | # y paramos la ejecución 32 | if [ ! -d "$DIRECTORIO_A_COPIAR" ]; then 33 | echo "No exixte el directorio a copiar." 34 | exit 1 35 | fi 36 | 37 | # si no exixte el directorio de los ficheros lo creamos 38 | if [ ! -d "$RUTA_FICHEROS" ]; then 39 | mkdirs "$RUTA_FICHEROS" 40 | fi 41 | 42 | # empaquetamos y comprimimos el DIRECTORIO_A_COPIAR 43 | # en FICHERO_COMPRIMIDO (mediante zip) 44 | zip -r "$FICHERO_COMPRIMIDO" "$DIRECTORIO_A_COPIAR" 45 | 46 | # guardar la fecha de la última copia total en FICHERO_ULTIMA_COPIA_TOTAL 47 | echo "$FECHA" > "$FICHERO_ULTIMA_COPIA_TOTAL" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/05-copias/miCrontab: -------------------------------------------------------------------------------- 1 | ###################################################### 2 | # minuto (0-59), # 3 | # | hora (0-23), # 4 | # | | día del mes (1-31), # 5 | # | | | mes (1-12), # 6 | # | | | | día de la semana (0-6 donde 0=Domingo) # 7 | # | | | | | comandos # 8 | # | | | | | | # 9 | ###################################################### 10 | * * * * * date > ~/ultimo-crontab.txt 11 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/arrays.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | declare -a ARRAY; 8 | 9 | ARRAY=("cero" "uno" [3]="tres") 10 | ARRAY[2]="dos" 11 | 12 | LENGTH=${#ARRAY[*]} 13 | 14 | for (( i=0; i= \$1 && $HORA_INICIAL < \$2 ) print \$0 }" > "$FICHERO_PROGRAMA_AWK" 127 | 128 | # ejecutamos el comando y guardamos el resultado en una variable 129 | CITA_SOLAPADA=$(more "$CITAS_FILE" | awk -f "$FICHERO_PROGRAMA_AWK") 130 | 131 | # si existe alguna cita que se solape 132 | if [ -n "$CITA_SOLAPADA" ]; then 133 | 134 | error "$LINEA_ERROR" "La hora inicial '$HORA_INICIAL' se solapa con la cita '$CITA_SOLAPADA'." 3 135 | fi 136 | } 137 | 138 | # función que comprueba que la hora final no se solapa con alguna cita ya introducida 139 | # $1 línea de error 140 | # $2 hora final 141 | function solape_hora_final() { 142 | 143 | # líenea error 144 | LINEA_ERROR="$1" 145 | 146 | # recogemos la hora final 147 | HORA_FINAL="$2" 148 | 149 | # fichero con el programa awk 150 | FICHERO_PROGRAMA_AWK="$HOME/awk-program.txt" 151 | 152 | # sentencia awk para buscar si ya existe una cita que se solape 153 | echo "{ if ( $HORA_FINAL > \$1 && $HORA_FINAL <= \$2 ) print \$0 }" > "$FICHERO_PROGRAMA_AWK" 154 | 155 | # ejecutamos el comando y guardamos el resultado en una variable 156 | CITA_SOLAPADA=$(more "$CITAS_FILE" | awk -f "$FICHERO_PROGRAMA_AWK") 157 | 158 | # si existe alguna cita que se solape 159 | if [ -n "$CITA_SOLAPADA" ]; then 160 | 161 | error "$LINEA_ERROR" "La hora final '$HORA_FINAL' se solapa con la cita '$CITA_SOLAPADA'." 3 162 | fi 163 | } 164 | 165 | # función que comprueba que no exista ya un nombre de paciente 166 | # $1 línea de error 167 | # $2 nombre del paciente a comprobar 168 | function nombre_paciente() { 169 | 170 | # líenea error 171 | LINEA_ERROR="$1" 172 | 173 | # recogemos el nombre del paciente 174 | NOMBRE_PACIENTE="$2" 175 | 176 | # si el nombre ya está en el fichero de citas 177 | if [ "$(grep "$NOMBRE_PACIENTE" "$CITAS_FILE" && echo 'SI')" == "SI" ]; then 178 | 179 | error "$LINEA_ERROR" "Nombre del paciente '$NOMBRE_PACIENTE' repetido." 4 180 | fi 181 | } 182 | 183 | # función que comprueba si ha habido algún error inexperado 184 | # $1 línea de error 185 | function error_inexperado() { 186 | 187 | # líenea error 188 | LINEA_ERROR="$1" 189 | 190 | # si ocurre algún error inexperado 191 | # shellcheck disable=SC2181 192 | if [ "$?" != "0" ]; then 193 | 194 | error "$LINEA_ERROR" "Error inexperado." 6 195 | fi 196 | } 197 | 198 | # función para añadir una cita 199 | # $1 hora incio cita 200 | # $2 hora final cita 201 | # $3 nombre del paciente 202 | function add() { 203 | 204 | # comprobamos que el número de parámetros sea igual a 3 205 | numero_parametros $LINENO 3 "$@" 206 | 207 | # inicializamos las variables con los valores de los parámetros introducidos 208 | HORA_INICIAL="$1" 209 | HORA_FINAL="$2" 210 | NOMBRE_PACIENTE=$3 211 | 212 | # comprobamos que el formato de la hora inicial sea el correcto 213 | formato_hora $LINENO "$HORA_INICIAL" 214 | 215 | # comprobamos que la hora inicial no se solape con alguna cita ya introducida 216 | solape_hora_inicial $LINENO "$HORA_INICIAL" 217 | 218 | # comprobamos que el formato de la hora final sea el correcto 219 | formato_hora $LINENO "$HORA_FINAL" 220 | 221 | # comprobamos que la hora final no se solape con alguna cita ya introducida 222 | solape_hora_final $LINENO "$HORA_FINAL" 223 | 224 | # comprobamos que no exista ya el nombre del paciente 225 | nombre_paciente $LINENO "$NOMBRE_PACIENTE" 226 | 227 | # grabamos al final del fichero 228 | echo "$HORA_INICIAL" "$HORA_FINAL" "$NOMBRE_PACIENTE" >> "$CITAS_FILE" 229 | 230 | # comprobamos que no haya habido ningún error inexperado 231 | error_inexperado $LINENO 232 | } 233 | 234 | # función de búsqueda por NOMBRE_PACIENTE 235 | # $1 patrón de búsqueda 236 | function search() { 237 | 238 | # comprobamos que el número de parámetros sea igual a 1 239 | numero_parametros $LINENO 1 "$@" 240 | 241 | PATRON="$1" 242 | 243 | # buscamos el patrón introducido en el fichero de las citas 244 | grep "$PATRON" "$CITAS_FILE" 245 | 246 | # comprobamos que no haya habido ningún error inexperado 247 | error_inexperado $LINENO 248 | } 249 | 250 | # función de búsqueda por HORA_INICIAL 251 | # $1 hora inicial 252 | function init() { 253 | 254 | # comprobamos que el número de parámetros sea igual a 1 255 | numero_parametros $LINENO 1 "$@" 256 | 257 | HORA_INICIAL="$1" 258 | 259 | # comprobamos que el formato de la hora inicial sea el correcto 260 | formato_hora $LINENO "$HORA_INICIAL" 261 | 262 | # buscamos la hora inicial en el fichero de las citas 263 | grep -E "^$HORA_INICIAL.*$" $CITAS_FILE 264 | 265 | # comprobamos que no haya habido ningún error inexperado 266 | error_inexperado $LINENO 267 | } 268 | 269 | # función de búsqueda por HORA_FINAL 270 | # $1 hora final 271 | function end() { 272 | 273 | # comprobamos que el número de parámetros sea igual a 1 274 | numero_parametros $LINENO 1 "$@" 275 | 276 | HORA_FINAL="$1" 277 | 278 | # comprobamos que el formato de la hora final sea el correcto 279 | formato_hora "$LINENO" "$HORA_FINAL" 280 | 281 | # buscamos la hora final en el fichero de las citas 282 | grep -E "^...$HORA_FINAL.*$" "$CITAS_FILE" 283 | 284 | # comprobamos que no haya habido ningún error inexperado 285 | error_inexperado $LINENO 286 | } 287 | 288 | # función de listado ordenados por NOMBRE_PACIENTE 289 | function name() { 290 | 291 | # comprobamos que el número de parámetros sea igual a 0 292 | numero_parametros $LINENO 0 "$@" 293 | 294 | # ordenamos el fichero de las citas por la tercera columna 295 | sort -k 3 $CITAS_FILE 296 | 297 | # comprobamos que no haya habido ningún error inexperado 298 | error_inexperado $LINENO 299 | } 300 | 301 | # función de listado ordenados por HORA_INICIAL 302 | function hour() { 303 | 304 | # comprobamos que el número de parámetros sea igual a 0 305 | numero_parametros $LINENO 0 "$@" 306 | 307 | # ordenamos el fichero de las citas por la primera columna en formato numérico 308 | sort -nk 1 $CITAS_FILE 309 | 310 | # comprobamos que no haya habido ningún error inexperado 311 | error_inexperado $LINENO 312 | } 313 | 314 | # vemos si tenemos acceso al fichero de las citas 315 | touch $CITAS_FILE 316 | 317 | # comprobamos que no haya habido ningún error inexperado 318 | error_inexperado 319 | 320 | # recogemos la opción selecionada 321 | OPCION="$1" 322 | 323 | # eliminamos el primer parámetro 324 | shift 325 | 326 | # dependiendo de la opción seleccionada 327 | case $OPCION in 328 | -h|--help) ayuda;; 329 | -a|--add) add "$@";; 330 | -s|--search) search "$@";; 331 | -i|--init) init "$@";; 332 | -e|--end) end "$@";; 333 | -n|--name) name "$@";; 334 | -o|--hour) hour "$@";; 335 | *) error $LINENO "Opción '$OPCION' inválida." 5;; 336 | esac 337 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/citas-flags.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script interfaz del script 'citas' 8 | 9 | # variables globales 10 | CITAS_SCRIPT=./citas 11 | 12 | # función de ayuda 13 | function ayuda() { 14 | cat << DESCRIPCION_AYUDA 15 | SYNOPIS 16 | $0 [OPCIONES] [HORA_INICIAL] [HORA_FINAL] [NOMBRE_PACIENTE] 17 | 18 | DESCRIPCIÓN 19 | Añade y busca citas de una consulta. 20 | 21 | OPCIONES 22 | -h --help Para mostrar un texto de ayuda. 23 | -a --add Para añadir una cita con HORA_INICIAL, HORA_FINAL, y NOMBRE_PACIENTE. 24 | -s --search Para buscar los pacientes que contengan PATRÓN. 25 | -i --init Para buscar las citas que empiecen a HORA_INICIAL. 26 | -e --end Para buscar las citas que terminen a HORA_FINAL. 27 | -n --name Para listar todas las citas ordenadas por NOMBRE_PACIENTE. 28 | -o --hour Para listar todas las citas ordenadas por HORA_INICIAL. 29 | 30 | CÓDIGOS DE RETORNO 31 | 0 Si no hay ningún error. 32 | 1 Si el número de parámetros es incorrecto. 33 | 2 Si el formato de los parámetros es incorrecto. 34 | 3 Si al añadir una cita se solapa con otra ya introducida. 35 | 4 Si al añadir una cita ya existe NOMBRE_PACIENTE. 36 | 5 Si se introduce una opción inválida. 37 | 6 Si ocurre otro error no mencionado. 38 | DESCRIPCION_AYUDA 39 | } 40 | 41 | 42 | # función de error 43 | # $1 línea de error 44 | # $2 mensaje de error 45 | function error() { 46 | 47 | echo "$0: línea $1: $2" 48 | } 49 | 50 | # función para añadir una cita 51 | function add() { 52 | 53 | echo "AÑADIR UNA CITA NUEVA" 54 | $CITAS_SCRIPT --add "$@" 55 | echo "----------------------------------------" 56 | } 57 | 58 | # función de búsqueda 59 | function search() { 60 | 61 | echo "BUSCAR POR PATRÓN ($*)" 62 | $CITAS_SCRIPT --search "$@" 63 | echo "----------------------------------------" 64 | } 65 | 66 | # función de búsqueda por hora inicial 67 | function init() { 68 | 69 | echo "BUSCAR POR HORA INICIAL" 70 | $CITAS_SCRIPT --init "$@" 71 | echo "----------------------------------------" 72 | } 73 | 74 | # función de búsqueda por hora final 75 | function end() { 76 | 77 | echo "BUSCAR POR HORA FINAL" 78 | $CITAS_SCRIPT --end "$@" 79 | echo "----------------------------------------" 80 | } 81 | 82 | # función de listado ordenados por nombres 83 | function name() { 84 | 85 | echo "LISTADO ORDENADO POR NOMBRE DEL PACIENTE" 86 | $CITAS_SCRIPT --name 87 | echo "----------------------------------------" 88 | } 89 | 90 | # función de listado ordenados por hora de inicial 91 | function hour() { 92 | 93 | echo "LISTADO ORDENADO POR HORA INICIAL" 94 | $CITAS_SCRIPT --hour 95 | echo "----------------------------------------" 96 | } 97 | 98 | # función opción invalida 99 | function opcion_invalida() { 100 | echo "Opción '$1' inválida." 101 | exit 5 102 | } 103 | 104 | while getopts "ha:s:lt" option ; do 105 | case "$option" in 106 | h) ayuda ;; 107 | a) add "$OPTARG" ;; 108 | s) search "$OPTARG" ;; 109 | i) init "$OPTARG" ;; 110 | e) end "$OPTARG" ;; 111 | n) name ;; 112 | o) hour ;; 113 | *) opcion_invalida "$option" ;; 114 | esac 115 | done 116 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/citas-menu.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # script interfaz del script 'citas' 8 | 9 | # variables globales 10 | CITAS_SCRIPT=./citas 11 | 12 | # función de ayuda 13 | function ayuda() { 14 | cat << DESCRIPCION_AYUDA 15 | SYNOPIS 16 | $0 [OPCIONES] 17 | 18 | DESCRIPCIÓN 19 | Añade y busca citas HORA_INICIAL, HORA_FINAL y NOMBRE_PACIENTE. 20 | 21 | OPCIONES 22 | -h --help Muesta esta ayuda. 23 | 24 | CODIGOS DE RETORNO 25 | 0 Si no hay ningún error. 26 | DESCRIPCION_AYUDA 27 | } 28 | 29 | # función menu 30 | function menu() { 31 | cat << DESCRIPCION_MENU 32 | 33 | +---------------------------------------------------------------------+ 34 | | MENU DE CITAS | 35 | +---------------------------------------------------------------------+ 36 | | a. Añadir una cita con HORA_INICIAL, HORA_FINAL, y NOMBRE_PACIENTE. | 37 | | s. Buscar los pacientes que contengan PATRÓN. | 38 | | i. Buscar las citas que empiecen a HORA_INICIAL. | 39 | | e. Buscar las citas que terminen a HORA_FINAL. | 40 | | n. Listar todas las citas ordenadas por NOMBRE_PACIENTE. | 41 | | o. Listar todas las citas ordenadas por HORA_INICIAL. | 42 | | s. Salir del programa. | 43 | +---------------------------------------------------------------------+ 44 | 45 | DESCRIPCION_MENU 46 | } 47 | 48 | # función de error 49 | # $1 línea de error 50 | # $2 mensaje de error 51 | function error() { 52 | 53 | echo "$0: línea $1: $2" 54 | } 55 | 56 | # función para añadir una cita 57 | function add() { 58 | 59 | echo "AÑADIR UNA CITA NUEVA" 60 | read -r -p "Introduce la hora inicial (de 00 a 23): " HORA_INICIAL 61 | read -r -p "Introduce la hora final (de 00 a 23): " HORA_FINAL 62 | read -r -p "Introduce el nombre del paciente: " NOMBRE_PACIENTE 63 | $CITAS_SCRIPT --add "$HORA_INICIAL" "$HORA_FINAL" "$NOMBRE_PACIENTE" 64 | } 65 | 66 | # función de búsqueda 67 | function search() { 68 | 69 | echo "BUSCAR POR HORA INICIAL, HORA FINAL o NOMBRE DEL PACIENTE" 70 | read -r -p "Introduce un patrón de búsqueda: " PATRON 71 | $CITAS_SCRIPT --search "$PATRON" 72 | } 73 | 74 | # función de búsqueda por hora inicial 75 | function init() { 76 | 77 | echo "BUSCAR POR HORA INICIAL" 78 | read -r -p "Introduce la hora inicial (de 00 a 23): " HORA_INICIAL 79 | $CITAS_SCRIPT --init "$HORA_INICIAL" 80 | } 81 | 82 | # función de búsqueda por hora final 83 | function end() { 84 | 85 | echo "BUSCAR POR HORA FINAL" 86 | read -r -p "Introduce la hora final (de 00 a 23): " HORA_FINAL 87 | $CITAS_SCRIPT --end "$HORA_FINAL" 88 | } 89 | 90 | # función de listado ordenados por nombres 91 | function name() { 92 | 93 | echo "LISTADO ORDENADO POR NOMBRE DEL PACIENTE" 94 | $CITAS_SCRIPT --name 95 | } 96 | 97 | # función de listado ordenados por hora de inicial 98 | function hour() { 99 | 100 | echo "LISTADO ORDENADO POR HORA INICIAL" 101 | $CITAS_SCRIPT --hour 102 | } 103 | 104 | # función para salir del programa 105 | function salir() { 106 | 107 | exit 0 108 | } 109 | 110 | # función elegir_menu 111 | function elegir_menu() { 112 | 113 | menu 114 | read -r -p "Elige una opción: " OPCION 115 | clear 116 | 117 | case $OPCION in 118 | a) add ;; 119 | s) search ;; 120 | i) init ;; 121 | e) end ;; 122 | n) name ;; 123 | o) hour ;; 124 | s) salir ;; 125 | *) error $LINENO "Opción $OPCION inválida." ;; 126 | esac 127 | 128 | elegir_menu 129 | } 130 | 131 | 132 | parametros() { 133 | # si primer parámetro == '-h' o == '--help' 134 | if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then 135 | ayuda 136 | exit 0 137 | fi 138 | } 139 | 140 | if [ $# -gt 0 ]; then 141 | parametros "$1" 142 | fi 143 | 144 | clear 145 | 146 | elegir_menu 147 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/elevado: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # si el número de parámetros es distinto de 2 8 | if [ $# -ne 2 ]; then 9 | echo "Para ejecutar este script se necesitan 2 números." 10 | exit 2 11 | fi 12 | 13 | #inicializamos variables 14 | ELEVADO=1 15 | BASE="$1" 16 | EXPONENTE="$2" 17 | 18 | # para cada parámetro introducido 19 | for ((CONTADOR=0; CONTADOR<"$EXPONENTE"; CONTADOR++)); do 20 | 21 | ELEVADO=$(echo "$ELEVADO" "$BASE" | awk '{ print $1*$2 }') 22 | 23 | done 24 | 25 | echo "$ELEVADO" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/jaula: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # función que verifica que el número de parámetros es correcto 8 | function verificarNumeroParametros() { 9 | 10 | # si el número de parámetros es igual a 0 11 | if [ "$#" == "0" ]; then 12 | 13 | # muestra un mensaje de error y sale 14 | echo "Hay que introducir al menos un parámetro." 15 | exit 1 16 | fi 17 | } 18 | 19 | # funcion que crea la jaula si no existe 20 | function crearJaula() { 21 | 22 | JAULA=~/.jaula 23 | 24 | if [ -e $JAULA ]; then 25 | 26 | # si la jaula existe y no es un directorio 27 | if [ ! -d $JAULA ]; then 28 | 29 | # muestra un mensaje de error y sale 30 | echo "El fichero '~/.jaula' no es un directorio." 31 | exit 3 32 | fi 33 | 34 | else 35 | 36 | # creamos la jaula 37 | mkdir $JAULA 38 | fi 39 | } 40 | 41 | # función que mueve a la jaula los ficheros pasados por parámetro 42 | function moverFicheros() { 43 | 44 | # iteramos sobre los parámetros 45 | for i in "$@"; do 46 | 47 | FICHERO=$i 48 | 49 | # si el fichero pasado por parámeto no existe 50 | if [ ! -e "$FICHERO" ]; then 51 | 52 | # muestra un mensaje de error y sale 53 | echo "El fichero '$FICHERO' no existe." 54 | exit 2 55 | fi 56 | 57 | # mueve el fichero a la jaula 58 | mv "$FICHERO" "$JAULA" 59 | 60 | done 61 | } 62 | 63 | verificarNumeroParametros "$@" 64 | crearJaula 65 | moverFicheros "$@" 66 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/ordena: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | # si el número de parámetros es distinto de 0 8 | if [ "$#" != "0" ]; then 9 | 10 | # muestra un mensaje de error y sale 11 | echo "No se permiten parámetros." 12 | exit 1 13 | fi 14 | 15 | # muestra el listado ordenado de menor a mayor por el tamaño 16 | # sacando sólo el nombre del archivo y el número de línea 17 | # shellcheck disable=SC2012 18 | ls -l | sort -nk 5 | awk '{ print $8 }' | nl 19 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/quoting.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | test () { 8 | 9 | echo "dollar 1" 10 | echo $1 11 | 12 | echo "dollar *" 13 | echo $* 14 | 15 | echo "dollar @" 16 | echo $@ 17 | 18 | echo "dollar 1 con doble comilla" 19 | echo "$1" 20 | 21 | echo "dollar * con doble comilla" 22 | echo "$*" 23 | 24 | echo "dollar @ con doble comilla" 25 | echo "$@" 26 | 27 | echo ">>>>>>>>>>>>>>>>>>>>>>>>>for dollar *" 28 | for i in $*; do echo "$i"; done 29 | 30 | echo ">>>>>>>>>>>>>>>>>>>>>>>>>for dollar @" 31 | for i in $@; do echo "$i"; done 32 | 33 | echo ">>>>>>>>>>>>>>>>>>>>>>>>>for dollar * con doble comilla" 34 | for i in "$*"; do echo "$i"; done 35 | 36 | echo ">>>>>>>>>>>>>>>>>>>>>>>>>for dollar @ con doble comilla" 37 | for i in "$@"; do echo "$i"; done 38 | } 39 | 40 | echo "asterisco" 41 | 42 | test * 43 | 44 | echo "===========================" 45 | echo "asterisco con doble comilla" 46 | 47 | test "*" -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/roles-con-awk.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | awk -f roles.awk roles.csv 8 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/roles-sin-awk.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -o errexit # the script ends if a command fails 4 | set -o pipefail # the script ends if a command fails in a pipe 5 | set -o nounset # the script ends if it uses an undeclared variable 6 | 7 | ROLES_FILE=./roles.csv 8 | 9 | ROLES=$(cut -d : -f 2 $ROLES_FILE | sed 's/,/\n/g' | sort | uniq) 10 | shift # pasamos al siguiente parámetro 11 | 12 | for ROL in $ROLES; do 13 | 14 | echo "$ROL" 15 | NAMES=$(grep -E "$ROL $ROLES_FILE" | cut -d : -f 1) 16 | 17 | echo " -> $NAMES" 18 | done 19 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/roles.awk: -------------------------------------------------------------------------------- 1 | # esto se ejecutará solo una vez al principio 2 | BEGIN { 3 | FS = ",|:" 4 | } 5 | 6 | # esto se ejecutará para cada una de las líneas del fichero 7 | { 8 | nombre=$1 9 | 10 | for (N=2; N<=NF; N++) { 11 | 12 | rol=$N 13 | 14 | roles[rol]=""roles[rol]" "nombre 15 | } 16 | } 17 | 18 | # esto se ejecutará solo una vez al final 19 | END { 20 | for ( rol in roles) { 21 | print rol 22 | print " ->" roles[rol] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ejercicios-shell-script/solucion/06-varios/roles.csv: -------------------------------------------------------------------------------- 1 | Pepito:Jefe,Sistemas 2 | Fulanito:Jefe,Desarrollo 3 | Menganito:Operario,Sistemas,Desarrollo 4 | -------------------------------------------------------------------------------- /git-push.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | echo "**************************" 4 | echo "* PUSH CHANGES TO GITHUB *" 5 | echo "**************************" 6 | 7 | git status 8 | 9 | read -p "You want to continue? [y|*N*]: " OPTION 10 | 11 | if [ "$OPTION" == "y" ]; then 12 | 13 | read -p "Write the commit message: " MESSAGE 14 | 15 | git add . && \ 16 | git commit -m "$MESSAGE" && \ 17 | git push 18 | fi 19 | --------------------------------------------------------------------------------