The linux shell. Shell Scripting desde 0
-
Upload
remigio-salvador-sanchez -
Category
Documents
-
view
1.159 -
download
7
description
Transcript of The linux shell. Shell Scripting desde 0
![Page 2: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/2.jpg)
¿Cómo es qué pueden llegar a ser tan anormales los humanos, siento la razasuperior, el “animal más inteligente”?
¿Quiénes son los irracionales?
![Page 3: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/3.jpg)
➢ Introducción
➢ Nuestro primer script
➢ Variables
➢ Comandos del sistema
➢ Estructuras condicionales
➢ Ciclos
➢ Ingresando datos
➢ Operadores
➢ Recomendaciones
➢ Agradecimientos
CONTENIDO:
![Page 4: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/4.jpg)
● El shell es un ambiente de programación capaz de automatizar casi cualquier cosa en su sistema Linux.
● El shell de uso más común en Linux es bash, pero existen otros (ksh, sh, entre otros)
INTRODUCCIÓN
![Page 5: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/5.jpg)
● El shell provee:
– Una interfase interactiva textual al sistema operativo.
– Un ambiente operacional.
– Facilidades para iniciar y administrar comandos y programas.
– Un lenguaje de programación.
INTRODUCCIÓN
![Page 6: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/6.jpg)
● Los scripts son archivos que contienen comandos a ser ejecutados por una shell.
● Puede ser otro comando que pueda teclear a partir del prompt.
- comando que invoque una utilidad
- Un programa compilado
- Otro script :)
INTRODUCCIÓN
![Page 7: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/7.jpg)
● Los scripts soportan varias características de programación como pueden ser: ciclos, variables, arreglos, funciones, etc.
● Redirecciones de salida y entrada, PIPES, Expansiones, control de trabajo (jobs)
● Comandos construidos de forma personalizada :)
INTRODUCCIÓN
![Page 8: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/8.jpg)
--- holaScript.sh ---
#!/bin/bash
clear
echo Hola script
--- holaScript.sh ---
NUESTRO PRIMER SCRIPT
![Page 9: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/9.jpg)
● De ambiente: Variables globales. Son pasadas a todos los procesos iniciados por el shell, incluyendo otros shells. Esto significa que los procesos hijo heredan el ambiente. Por convención se expresan en mayúsculas.
● De shell: Son variables locales. Son específicas al shell corriente y no son heredadas por procesos hijo. En bash, las variables de shell pasan a ser de ambiente cuando son exportadas.
VARIABLES
![Page 10: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/10.jpg)
● Muchas de las variables son necesarias para la ejecución de programas.
● Para que esas variables esten disponibles deben ser exportadas para convertirlas en variables de ambiente.
$ export MIVAR
● Para listar las variables de ambiente:
$ env
VARIABLES
![Page 11: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/11.jpg)
● $0 : Nombre del programa ó script.
● $# : Cantidad de argumentos.
● $1..$n : Argumentos según su posición en la línea de comandos.
● $@ : Lista de argumentos.
● $? : Resultado de la ejecución del ultimo comando.
● $$ : PID del shell actual.
VARIABLES
![Page 12: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/12.jpg)
--- variables3.sh ---
echo "Nombre del script: $0"
echo "Número de argumentos: $#"
echo "Lista de argumentos: $*"
echo "PID del proceso actual: $$"
echo "PID del proceso hijo: $!"
--- vairables3.sh ---
VARIABLES
![Page 13: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/13.jpg)
--- comando.sh ---
#!/bin/bash
HOLA="Hola, hoy es el día $(date +%j) del año."
echo $HOLA
--- comando.sh ---
COMANDOS DEL SISTEMA
![Page 14: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/14.jpg)
Cuando se asignan cadenas de caracteres que contiene espacios o caracteres especiales, la cadena debe estar encerrada entre apostrofes o comillas
El uso de comillas dentro de una cadena de caracteres permitira que cualquier variables dentro de las comillassea interpretado
Apostrofes y comillas
![Page 15: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/15.jpg)
--- comando.sh ---
#!/bin/bash
HOLA=”date +%j”
echo $HOLA
--- comando.sh ---
COMANDOS DEL SISTEMA
![Page 16: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/16.jpg)
--- comando.sh ---
#!/bin/bash
HOLA=`date +%j`
echo $HOLA
--- comando.sh ---
COMANDOS DEL SISTEMA
![Page 17: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/17.jpg)
--- variables.sh ---
#!/bin/bash
var=”test de cadenas”
var2=”Valor de la variable es $var”
echo $var2
--- variables.sh ---
COMANDOS DEL SISTEMA
![Page 18: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/18.jpg)
--- variables.sh ---
#!/bin/bash
var='test de cadenas'
var2='Valor de la variable es $var'
echo $var2
--- variables.sh ---
COMANDOS DEL SISTEMA
![Page 19: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/19.jpg)
● [ s1 = s2 ]: s1 coincide con s2
● [ s1 != s2 ]: s1 no coincide con s2
● [ s1 < s2 ]: s1 es alfabéticamente anterior a s2, con el locale actual
● [ s1 > s2 ]: s1 es alfabéticamente posterior a s2, con el locale actual
● [ -n s1 ]: s1 no es nulo (contiene uno o más caracteres)
● [ -z s1 ] : s1 es nulo
OPERADORES (CADENAS DE TEXTO)
![Page 20: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/20.jpg)
--- si2.sh ---
#!/bin/bash
if [ $(whoami) = root ]; then
echo “Hola ROOT”
else
echo “No eres root”
fi
--- si2.sh ---
ESTRUCTURA CONDICIONALES
![Page 21: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/21.jpg)
--- si3.sh ---
#!/bin/bash
if [ $USER = root ]; then
echo “El usuario es root”
elif [ $(whoami) = BugCon ]; then
echo “El usuario es BugCon”
else
echo “quien eres”
fi
--- si3.sh ---
ESTRUCTURA CONDICIONALES
![Page 22: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/22.jpg)
--- archivo.sh ---
#!/bin/bash
if [ -f "BUGCON.TXT" ]; then
echo el archivo existe
else
echo archivo no encontrado
fi
--- archivo.sh ---
ESTRUCTURA CONDICIONALES
![Page 23: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/23.jpg)
--- leer.sh ---
#!/bin/bash
echo Por favor, introduzca su nombre:
read NOMBRE
echo "¡Hola $NOMBRE!"
--- leer.sh ---
INGRESANDO DATOS
![Page 24: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/24.jpg)
● + (adición)
● - (sustracción)
● * (producto)
● / (división)
● % (módulo)
● ** (exponenciación)
OPERADORES (ARITMETICOS)
![Page 25: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/25.jpg)
● [ a -lt b ] equivale a ((a < b))
● [a -gt b ] equivale a ((a > b))
● [a -le b ] equivale a ((a <= b))
● [a -ge b ] equivale a ((a >= b))
● [a -eq b ] equivale a ((a == b))
● [a -ne b ] equivale a ((a != b))
OPERADORES (RELACIONES ARITMETICAS)
![Page 26: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/26.jpg)
● && Y lógico (AND)
● || O lógico (OR)
OPERADORES (LOGICOS)
![Page 27: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/27.jpg)
–-d /ruta/archivo: Verdadero si archivo existe y es un directorio
–-e /ruta/archivo: Verdadero si archivo existe
–-f /ruta/archivo: Verdadero si archivo existe y es un archivo común
–-l /ruta/archivo: Verdadero si archivo existe y es un enlace suave
–-r /ruta/archivo: Verdadero si archivo existe y puede leerse
OPERADORES (SOBRE ARCHIVOS)
![Page 28: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/28.jpg)
-s /ruta/archivo: Verdadero si archivo existe y tiene tamaño mayor que 0
–-w /ruta/archivo: Verdadero si archivo existe y es escribible
–-x /ruta/archivo: Verdadero si archivo existe y es ejecutable
arch1 -ot arch2: Verdadero si arch1 es más viejo que arch2
OPERADORES (SOBRE ARCHIVOS)
![Page 29: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/29.jpg)
● El for es distinto a los de otros lenguajes de programación. Básicamente, le permite iterar sobre una serie de `palabras' contenidas dentro de una cadena.
CICLOS
![Page 30: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/30.jpg)
● El for es distinto a los de otros lenguajes de programación. Básicamente, le permite iterar sobre una serie de `palabras' contenidas dentro de una cadena.
● El while ejecuta un trozo de código si la expresión de control es verdadera, y termina cuando es falsa (o se encuentra una interrupción explícita dentro del código en ejecución)
CICLOS
![Page 31: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/31.jpg)
● El for es distinto a los de otros lenguajes de programación. Básicamente, le permite iterar sobre una serie de “palabras” contenidas dentro de una cadena.
● El while ejecuta un trozo de código si la expresión de control es verdadera, y termina cuando es falsa (o se encuentra una interrupción explícita dentro del código en ejecución).
● El until es casi idéntico al while, excepto en que el código se ejecuta mientras la expresión de control se evalúe como falsa.
CICLOS
![Page 32: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/32.jpg)
--- contador.sh ---
#!/bin/bash
clear
read -p "Introduce un numero: " numero
for (( a=0; a<=$numero; a++ ))
do
echo "$a"
done
--- contador.sh ---
CICLOS
![Page 33: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/33.jpg)
--- mientras.sh ---
#!/bin/bash
CONTADOR=0
while [ $CONTADOR -lt 10 ]; do
echo El contador es $CONTADOR
let CONTADOR=CONTADOR+1
done
--- mientras.sh ---
CICLOS
![Page 34: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/34.jpg)
--- until.sh ---
#!/bin/bash
CONTADOR=20
until [ $CONTADOR -lt 10 ]; do
echo CONTADOR $CONTADOR
let CONTADOR-=1
done
--- until.sh ---
CICLOS
![Page 35: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/35.jpg)
--- caso.sh ---
#!/bin/bash
echo "Introduce un numero entre 1 y 5: "
read num
case $num in
1) echo "El valor de num es 1.";;
2) echo "El valor de num es 2.";;
3) echo "El valor de num es 3.";;
4) echo "El valor de num es 4.";;
5) echo "El valor de num es 5.";;
0|6) echo "NUMERO FUERA DE RANGO.";;
*) echo "valor no reconocido";;
esac
--- caso.sh ---
CICLOS
![Page 36: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/36.jpg)
Script (ejercicio.sh) que haga:
● Una carpeta (BUGCON)
● Una serie de archivos (10 archivos) dentro de la carpeta BUGCON
● Comprima la carpeta de BUGCON
●
● PREMIO AL QUE LO REALICE :)
EJERCICIO
![Page 37: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/37.jpg)
● ¡Lean!
RECOMENDACIONES
![Page 38: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/38.jpg)
● ¡Lean!
● Crond + script
RECOMENDACIONES
![Page 39: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/39.jpg)
● ¡Lean!
● Crond + script
● Webmin + script
RECOMENDACIONES
![Page 40: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/40.jpg)
● ¡Lean!
● Crond + script
● Webmin + script
● Script con Expect
RECOMENDACIONES
![Page 41: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/41.jpg)
AGRADECIMIENTOS
Gracias a ustedes por su atención Y
A los organizadores por todas facilidades prestadas
![Page 42: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/42.jpg)
DEDICADO A:
Mi familia,
Alondra <3
y a amigos (B) xD
![Page 43: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/43.jpg)
CONTACTO:
Remigio Salvador Sánchez
@remitos
[email protected]@hotmail.com
http://vkn-side.blogspot.mx
![Page 44: The linux shell. Shell Scripting desde 0](https://reader036.fdocuments.ec/reader036/viewer/2022082310/54856133b47959d30c8b4e4a/html5/thumbnails/44.jpg)
FUENTES:
Shell Scripting en LinuxRoberto Gómez Cárdenas
[email protected]://homepage.cem.itesm.mx/rogomez
Creación de scriptDocumentos Aula SUN UCM
de Software LibreSergio VelascoAlicia Martín.
Mayo 2008.