Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
Folder with scripts
To create this post, we are going to create a folder where we will save all the scripts
!mkdir scripts_bash
First script
Execution binary specification
In Linux, you can specify which program to use to execute a file by putting #!<binary path>
on the first line, for example, if we create a .py
file, we can indicate that it should be executed with Python by putting #!/usr/bin/python3
on the first line. In our case, since we are creating a terminal script, we put #!/bin/bash
on the first line.
If execution permissions are given to the file, it can be executed directly without specifying the program with which it should be run. That is, the .py
no longer needs to be executed via python script.py
, but can be executed via ./script.py
. In our case, instead of running the file using bash script.sh
, we can run it using ./script.sh
.
Comments in bash scripts
If we want to introduce a comment, it would be enough to start the line with #
.
# This is a single-line comment
If we want to introduce several lines of comments, we have to start with :#
and end with #
: '
This is a multi-line comment
that extends across multiple lines.
''
Printing to the screen with the echo
command
If we want to print to the screen, we use the echo
command followed by what we want to print.
%%writefile scripts_bash/01_primerScript.sh#!/bin/bash# Comentario de una sola linea: 'Comentario de variaslineas'echo "Hola mundo"
Writing scripts_bash/01_primerScript.sh
We give execution permissions and run the script
!chmod +x scripts_bash/01_primerScript.sh && ./scripts_bash/01_primerScript.sh
Hola mundo
Variable declaration
There are two types of variables: user variables
and environment variables
To create a variable, it is enough to declare it by entering the name we want, followed by =
and the value.
To print the value of a variable with echo
, you have to reference it using $<variable name>
echo "Variable = $<variable name>"
%%writefile scripts_bash/02_variables.sh#!/bin/bashopcion=1nombre="Juan"echo "Opcion: $opcion"echo "Nombre: $nombre"
Writing scripts_bash/02_variables.sh
!chmod +x scripts_bash/02_variables.sh && ./scripts_bash/02_variables.sh
Opcion: 1Nombre: Juan
Scope of variables
Variables created are only accessible from the script, that is, their scope is within the script.
Exporting Variables
We can export variables so that they are accessible by other scripts. To do this, we first export the variable using the export
command and then run, within the script, the second script to which we want to pass the variable.
%%writefile scripts_bash/02_variables.sh#!/bin/bashopcion=1nombre="Juan"echo "Opcion: $opcion"echo "Nombre: $nombre"# Exportar variable nombreecho "export nombre=$nombre"export nombre# Ejecutar script de importacionecho ""echo "Ejecutando script de importacion"./scripts_bash/02_variables_importacion.sh
Overwriting scripts_bash/02_variables.sh
%%writefile scripts_bash/02_variables_importacion.sh#!/bin/bashecho "Nombre importado: $nombre"
Writing scripts_bash/02_variables_importacion.sh
!chmod +x scripts_bash/02_variables.sh && chmod +x scripts_bash/02_variables_importacion.sh && ./scripts_bash/02_variables.sh
Opcion: 1Nombre: Juanexport nombre=JuanEjecutando script de importacionNombre importado: Juan
The second script has to be executed within the first script. If we now run the second script, we don't have the variable
!chmod +x scripts_bash/02_variables_importacion.sh && ./scripts_bash/02_variables_importacion.sh
Nombre importado:
If we want it to be accessible from any second script, without having to run it inside the first script, we need to export the variable to an environment variable.
Types of operators
Below, we show all possible operators
%%writefile scripts_bash/03_operadores.sh#!/bin/bash# Asignación de variablesx=10y=20echo "x = $x"echo "y = $y"# Operadores aritméticosecho ""echo "Operadores aritméticos"echo "x + y = $((x + y))"echo "x - y = $((x - y))"echo "x * y = $((x * y))"echo "x / y = $((x / y))"echo "x % y = $((x % y))"# Operadores de comparaciónecho ""echo "Operadores de comparación"if [ "$x" -eq "$y" ]; thenecho "x es igual a y"elseecho "x no es igual a y"fiif [ "$x" -ne "$y" ]; thenecho "x no es igual a y"elseecho "x es igual a y"fiif [ "$x" -lt "$y" ]; thenecho "x es menor que y"elseecho "x no es menor que y"fiif [ "$x" -gt "$y" ]; thenecho "x es mayor que y"elseecho "x no es mayor que y"fi# Operadores de cadenaecho ""echo "Operadores de cadena"if [ "$a" = "$b" ]; thenecho "a es igual a b"elseecho "a no es igual a b"fiif [ "$a" != "$b" ]; thenecho "a no es igual a b"elseecho "a es igual a b"fiif [ -z "$a" ]; thenecho "a es una cadena vacía"elseecho "a no es una cadena vacía"fiif [ -n "$a" ]; thenecho "a no es una cadena vacía"elseecho "a es una cadena vacía"fi# Operadores de archivoecho ""echo "Operadores de archivo"if [ -e "/path/to/file" ]; thenecho "El archivo existe"elseecho "El archivo no existe"fiif [ -f "/path/to/file" ]; thenecho "Es un archivo regular"elseecho "No es un archivo regular"fiif [ -d "/path/to/dir" ]; thenecho "Es un directorio"elseecho "No es un directorio"fi
Overwriting scripts_bash/03_operadores.sh
!chmod +x scripts_bash/03_operadores.sh && ./scripts_bash/03_operadores.sh
x = 10y = 20Operadores aritméticosx + y = 30x - y = -10x * y = 200x / y = 0x % y = 10Operadores de comparaciónx no es igual a yx no es igual a yx es menor que yx no es mayor que yOperadores de cadenaa es igual a ba es igual a ba es una cadena vacíaa es una cadena vacíaOperadores de archivoEl archivo no existeNo es un archivo regularNo es un directorio
Passing Arguments
Arguments can be passed to scripts, once inside the script we can use them in the following way
- By argument number: in this case they will be named as
$1
,$2
, etc. But if the number of arguments is greater than 9, that is, more than 2 digits are needed to name it, in that case the number will be identified within braces,${1}
,${2}
, ..., ${10}, ${11}, etc - If we refer to the argument
$0
we are getting the name of the file - If we want all the arguments, we do it through
$*
- If what we want is the number of arguments we have, we get it through
$#
* If we want to know the exit status of the last command, we can do so using$?
- If we want to know the
PID
of the script, we can find it using$$
- We can replace the value of a string in an argument using
${
, meaning that if we have/string to be replaced/new string} ${1/hola/hello}
it will replace the wordhola
with the wordhello
in argument 1 - However, if we use
${
, it will only replace the string in the argument if the argument starts with that string./#string to be replaced/new string}
%%writefile scripts_bash/04_argumentos.sh#!/bin/bash# Pasos de argumentos simplesecho "Primer argumento: $1"echo "Segundo argumento: $2"echo "Tercer argumento: $3"# Accediendo a todos los argumentosecho "Todos los argumentos: $*"# Accediendo al número de argumentosecho "Número de argumentos: $#"# Accediendo al nombre del scriptecho "Nombre del script: $0"# Accediendo al código de salida del último comando ejecutadoecho "Código de salida del último comando: $?"# Accediendo al PID del scriptecho "PID del script: $$"# Accediendo a los argumentos con índicesecho "Argumento 3: ${3}"echo "Argumento 2: ${2}"# Accediendo a los argumentos con índices y longitud máximaecho "Argumento 3 con longitud máxima de 2 caracteres: ${3:0:2}"echo "Argumento 2 con longitud máxima de 3 caracteres: ${2:0:3}"# Reemplazando argumentos con índices y longitud máximaecho "Reemplazando argumento 3: ${3/arg/ARG}"echo "Reemplazando argumento 2: $ {2/arg/ARG}"# Accediendo a los argumentos con índices y patrones de reemplazoecho "Reemplazando patrón en argumento 3: ${3/#tercer/TERCER}"echo "Reemplazando patrón en argumento 2: ${2/#arg/ARG}"
Overwriting scripts_bash/04_argumentos.sh
!arg1="primer argumento" && arg2="segundo argumento" && arg3="tercer argumento" && chmod +x scripts_bash/04_argumentos.sh && ./scripts_bash/04_argumentos.sh "$arg1" "$arg2" "$arg3"
Primer argumento: primer argumentoSegundo argumento: segundo argumentoTercer argumento: tercer argumentoTodos los argumentos: primer argumento segundo argumento tercer argumentoNúmero de argumentos: 3Nombre del script: ./scripts_bash/04_argumentos.shCódigo de salida del último comando: 0PID del script: 11644Argumento 3: tercer argumentoArgumento 2: segundo argumentoArgumento 3 con longitud máxima de 2 caracteres: teArgumento 2 con longitud máxima de 3 caracteres: segReemplazando argumento 3: tercer ARGumentoReemplazando argumento 2: segundo ARGumentoReemplazando patrón en argumento 3: tercer argumentoReemplazando patrón en argumento 2: segundo argumento
Running commands and saving them to a variable
We have two ways to run a command and save its output to a variable
- By using
variable=command
* By usingvariable=$(command)
%%writefile scripts_bash/05_variables_comandos.sh#!/bin/bashpath=$(pwd)infokernel=`uname -a`echo "El directorio actual es: $path"echo "La información del kernel es: $infokernel"
Overwriting scripts_bash/05_variables_comandos.sh
!chmod +x scripts_bash/05_variables_comandos.sh && ./scripts_bash/05_variables_comandos.sh
El directorio actual es: /home/wallabot/Documentos/web/portafolio/postsLa información del kernel es: Linux wallabot 5.15.0-57-generic #63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Debugging
There are two ways to debug in bash scripting
- Using
-v
: Detailed execution of a script line by line* Using-x
: Script information display
!bash -v scripts_bash/05_variables_comandos.sh
#!/bin/bashpath=$(pwd)infokernel=`uname -a`echo "El directorio actual es: $path"El directorio actual es: /home/wallabot/Documentos/web/portafolio/postsecho "La información del kernel es: $infokernel"La información del kernel es: Linux wallabot 5.15.0-57-generic #63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
!bash -x scripts_bash/05_variables_comandos.sh
++ pwd+ path=/home/wallabot/Documentos/web/portafolio/posts++ uname -a+ infokernel='Linux wallabot 5.15.0-57-generic #63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux'+ echo 'El directorio actual es: /home/wallabot/Documentos/web/portafolio/posts'El directorio actual es: /home/wallabot/Documentos/web/portafolio/posts+ echo 'La información del kernel es: Linux wallabot 5.15.0-57-generic #63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux'La información del kernel es: Linux wallabot 5.15.0-57-generic #63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Get user information
Getting Information Using the echo
and read
Commands
We have three ways to get user information
- Using the command
echo -n
. With the-n
flag we indicate that we do not want a newline to be printed at the end of theecho
. For example,echo -n "Enter data: "
, with this command we ask for input and the cursor will remain on the same line, there will be no newline. - Using the
read
command. With this command, the program will wait for the user to enter data, ending with a newline. What the user enters will be stored in the variableREPLY
. If you want the variable where the user's input is stored to have a different name, you should useread [variable]
, for example, the commandread myVariable
will store the user's input in the variablemyVariable
. - By using the command
$REPLY
or$(variable)
we access the data entered by the user.
%%writefile scripts_bash/06_leer_informacion.sh#!/bin/bashoption=0backupName=""echo "Programa de utilidades"echo -n "Ingresar una opción: "readoption=$REPLYecho ""echo -n "Ingresar un nombre: "read backupNameecho ""echo "Opción: $option, backupName: $backupName"
Overwriting scripts_bash/06_leer_informacion.sh
As in a Jupyter notebook I can't feed the data as it asks for it, I feed it beforehand in a pipe |
!chmod +x scripts_bash/06_leer_informacion.sh && echo "1 nombreprueba" | ./scripts_bash/06_leer_informacion.sh
Programa de utilidadesIngresar una opción:Ingresar un nombre:Opción: 1, backupName: nombreprueba
Get information only using the read
command
Another way to get information is to use only the read
command, the syntax would be
read -p "Prompt message:" [variable]
The flag -p
indicates that the message Prompt message:
will be displayed before waiting for the user to enter the data. If no variable name is specified, the data will be stored in the variable REPLY
.
%%writefile scripts_bash/06_leer_informacion.sh#!/bin/bashoption=0backupName=""echo "Programa de utilidades"echo -n "Ingresar una opción: "readoption1=$REPLYecho ""echo -n "Ingresar un nombre: "read backupNameecho ""read -p "Ingresar otra opción: " option2echo ""echo "Opción: $option1-$option2, backupName: $backupName"
Overwriting scripts_bash/06_leer_informacion.sh
!chmod +x scripts_bash/06_leer_informacion.sh && echo "1 nombreprueba 2" | ./scripts_bash/06_leer_informacion.sh
Programa de utilidadesIngresar una opción:Ingresar un nombre:Opción: 1-2, backupName: nombreprueba
Validate the user information
To validate user information, the best approach would be to use regular expressions. Here is a post where I explain them.
Additionally, we can specify the number of characters we want the user to input when using read
. For this, we use the -n
flag, which, if not followed by a number, will wait until the user enters a newline. If it is followed by a number, it will wait until the user inputs that number of characters.
%%writefile scripts_bash/07_validar_informacion.sh#!/bin/bashoption=0backupName=""echo "Programa de utilidades"echo -n "Ingresar una opción: "read -n1option1=$REPLYecho ""echo -n "Ingresar un nombre: "read -n4 backupNameecho ""read -p "Ingresar otra opción: " option2echo ""echo "Opción: $option1-$option2, backupName: $backupName"
Writing scripts_bash/07_validar_informacion.sh
!chmod +x scripts_bash/07_validar_informacion.sh && echo "1back2" | ./scripts_bash/07_validar_informacion.sh
Programa de utilidadesIngresar una opción:Ingresar un nombre:Opción: 1-2, backupName: back
If we want to input a confidential value, such as a key, we use the -s
(security) flag. This way, when the user enters the data, it will not be printed on the console.
%%writefile scripts_bash/07_validar_informacion.sh#!/bin/bashoption=0backupName=""echo "Programa de utilidades"echo -n "Ingresar una opción: "read -n1option1=$REPLYecho ""echo -n "Ingresar un nombre: "read -n4 backupNameecho ""read -p "Ingresar otra opción: " option2echo ""read -s -p "Password: " passwordecho ""echo "Opción: $option1-$option2, backupName: $backupName, password: $password"
Overwriting scripts_bash/07_validar_informacion.sh
!chmod +x scripts_bash/07_validar_informacion.sh && echo "1back2 1234" | ./scripts_bash/07_validar_informacion.sh
Programa de utilidadesIngresar una opción:Ingresar un nombre:Opción: 1-2, backupName: back, password: 1234
If else
The way to write if
-else
conditionals is:
if [[condition]]; then
statement
elif [[condition]]; then
statement
elsestatement
fi
It is important to emphasize that the conditions must be between two brackets [[]]
%%writefile scripts_bash/08_if_else.sh#!/bin/bashif [[ 1 > 2 ]]; thenecho "Verdadero"elif [[ 1 > 3 ]]; thenecho "Verdadero"elseecho "Falso"fi
Overwriting scripts_bash/08_if_else.sh
!chmod +x scripts_bash/08_if_else.sh && ./scripts_bash/08_if_else.sh
Falso
Let's see how nested if
s are created
%%writefile scripts_bash/08_if_else.sh#!/bin/bashif [[ 1 > 2 ]]; thenecho "Verdadero"elif [[ 1 > 3 ]]; thenecho "Verdadero"elseif [[ 1 > 4 ]]; thenecho "Verdadero pero falso"elseecho "Totalmente falso"fifi
Overwriting scripts_bash/08_if_else.sh
!chmod +x scripts_bash/08_if_else.sh && ./scripts_bash/08_if_else.sh
Totalmente falso
Conditional expressions
We have already seen how to create if
s, but it is necessary to explain how to create conditional expressions
If we are going to perform comparisons between strings
operation | command | example |
---|---|---|
greater than | `>` | [[ string1 > string2 ]] |
less than | `<` | [[ string1 < string2 ]] |
equal to | `==` | [[ string1 == string2 ]] |
equal to | `=` | [[ string1 = string2 ]] |
empty string | `-z` | [[ -z string ]] |
non-empty string | `-n` | [[ -n string ]] |
non-empty string | [[ string ]] |
If what we are going to do is make comparisons between numbers
operation | command | example |
---|---|---|
greater than | `-gt` | [[ number1 -gt number2 ]] |
greater than or equal to | `-ge` | [[ number1 -ge number2 ]] |
less than | `-lt` | [[ number1 -lt number2 ]] |
less than or equal to | `-le` | [[ number1 -le number2 ]] |
equal to | `-eq` | [[ number1 -eq number2 ]] |
not equal to | `-ne` | [[ number1 -ne number2 ]] |
If we want to check files or directories
operation | command | example |
---|---|---|
is a directory? | `-d` | [[ -d ]] |
is it a file? | `-f` | [[ -f |
exists? | `-e` | [[ -e or [[ -e ]] |
is writable? | `-w` | [[ -w |
is executable? | `-x` | [[ -x |
is it a link? | `-L` | [[ -L |
is it empty? | `-s` | [[ -s |
is owned by the user? | `-O` | [[ -O |
is it owned by the group? | `-G` | [[ -G |
was it modified? | `-N` | [[ -N |
Is file1 newer than file2? | `-nt` | [[ |
Is file1 older than file2? | `-ot` | [[ |
Is file1 the same as file2? | `-ef` | [[ |
Is file1 the same as file2? | `-ef` | [[ |
If we want to compare combined conditions with and
, or
and not
operation | command | example |
---|---|---|
and | `&&` | [[ |
or | ` |
If we want to negate the conditions
operation | command | example |
---|---|---|
not | `!` | [[ ! |
%%writefile scripts_bash/09_condicionales.sh#!/bin/bashecho "Comparando strings"string1="hola"string2="hola"string3="chao"string4=""if [[ $string1 > $string3 ]]; thenecho "$string1 es mayor que $string3"fiif [[ $string3 < $string1 ]]; thenecho "$string3 es menor que $string1"fiif [[ $string1 == $string2 ]]; thenecho "$string1 es igual que $string2"fiif [[ $string1 != $string3 ]]; thenecho "$string1 es diferente que $string3"fiif [[ -z $string4 ]]; thenecho "$string4 es una cadena vacía"fiif [[ -n $string3 ]]; thenecho "$string3 es una cadena no vacía"fiif [[ $string3 ]]; thenecho "$string3 es una cadena no vacía"fiecho -e " Comparando números"number1=10number2=10number3=20if [[ $number3 -gt $number1 ]]; thenecho "$number3 es mayor que $number1"fiif [[ $number3 -ge $number2 ]]; thenecho "$number3 es mayor o igual que $number2"fiif [[ $number1 -lt $number3 ]]; thenecho "$number1 es menor que $number3"fiif [[ $number1 -le $number2 ]]; thenecho "$number1 es menor o igual que $number2"fiif [[ $number1 -eq $number2 ]]; thenecho "$number1 es igual que $number2"fiif [[ $number1 -ne $number3 ]]; thenecho "$number1 es diferente que $number3"fiecho -e " Comparando archivos"file1="$PWD/2021-02-11-Introduccion-a-Python.ipynb"file2="$PWD/scripts_bash"file3="$PWD/mi_paquete_de_python"if [[ -d $file2 ]]; thenecho "$file2 es un directorio"fiif [[ -f $file1 ]]; thenecho "$file1 es un archivo"fiif [[ -e $file1 ]]; thenecho "$file1 existe"fiif [[ -r $file1 ]]; thenecho "$file1 es legible"fiif [[ -w $file1 ]]; thenecho "$file1 es escribible"fiif [[ -x $file1 ]]; thenecho "$file1 es ejecutable"fiif [[ -L $file1 ]]; thenecho "$file1 es un link"fiif [[ -s $file1 ]]; thenecho "$file1 tiene contenido"fiif [[ -O $file1 ]]; thenecho "$file1 es propiedad del usuario"fiif [[ -G $file1 ]]; thenecho "$file1 es propiedad del grupo"fiif [[ -N $file1 ]]; thenecho "$file1 fue modificado"fiif [[ $file1 -nt $file2 ]]; thenecho "$file1 es más nuevo que $file2"fiif [[ $file1 -ot $file2 ]]; thenecho "$file1 es más viejo que $file2"fiif [[ $file1 -ef $file1 ]]; thenecho "$file1 es el mismo archivo que $file2"fiecho -e " Comparando expresiones con AND"if [[ 2 > 1 && 3 > 1 ]]; thenecho "2 > 1 y 3 > 1"fiecho -e " Comparando expresiones con OR"if [[ 2 > 1 || 1 > 2 ]]; thenecho "2 > 1 o 1 > 2"fiecho -e " Comparando expresiones con NOT"if [[ ! 1 > 2 ]]; thenecho "1 > 2 no es cierto"fi
Overwriting scripts_bash/09_condicionales.sh
!chmod +x scripts_bash/09_condicionales.sh && ./scripts_bash/09_condicionales.sh
Comparando stringshola es mayor que chaochao es menor que holahola es igual que holahola es diferente que chaoes una cadena vacíachao es una cadena no vacíachao es una cadena no vacíaComparando números20 es mayor que 1020 es mayor o igual que 1010 es menor que 2010 es menor o igual que 1010 es igual que 1010 es diferente que 20Comparando archivos/home/wallabot/Documentos/web/portafolio/posts/scripts_bash es un directorio/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es un archivo/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb existe/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es legible/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es escribible/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb tiene contenido/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es propiedad del usuario/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es propiedad del grupo/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es más viejo que /home/wallabot/Documentos/web/portafolio/posts/scripts_bash/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb es el mismo archivo que /home/wallabot/Documentos/web/portafolio/posts/scripts_bashComparando expresiones con AND2 > 1 y 3 > 1Comparando expresiones con OR2 > 1 o 1 > 2Comparando expresiones con NOT1 > 2 no es cierto
case
statement
Let's see how the typical switch-case
is written, but in this case only case
is used.
case $variable in
<valor1>) <sentencia1>;;
<value2>) <statement2>;;
<value3>) <statement3>;;...
*) <statement that does not meet any of the above>
esac
%%writefile scripts_bash/10_case.sh#!/bin/bashvariable="amarillo"case $variable in"rojo") echo "Color rojo";;"verde") echo "Color verde";;"azul") echo "Color azul";;*) echo "Color desconocido";;esac
Writing scripts_bash/10_case.sh
!chmod +x scripts_bash/10_case.sh && ./scripts_bash/10_case.sh
Color desconocido
Arrays
Let's see how arrays behave in bash scripting
%%writefile scripts_bash/11_arrays.sh#!/bin/basharrayNumeros=(1 2 3 4 5)arrayStrings=("hola" "chao" "adios")arrayMixto=(1 "hola" 2 "chao" 3 "adios")arrayVacio=()arrayRango=({A..Z})echo "Arrays"echo "Array de números: ${arrayNumeros[*]}"echo "Array de strings: ${arrayStrings[*]}"echo "Array mixto: ${arrayMixto[*]}"echo "Array vacío: ${arrayVacio[*]}"echo "Array de rango: ${arrayRango[*]}"echo -e " Accediendo a elementos"echo "Primer elemento del array de números: ${arrayNumeros[0]}"echo "Segundo elemento del array de strings: ${arrayStrings[1]}"echo "Último elemento del array de números: ${arrayNumeros[-1]}"echo "Penúltimo elemento del array de strings: ${arrayStrings[-2]}"echo -e " Longitud de arrays"echo "Longitud del array de números: ${#arrayNumeros[*]}"echo "Longitud del array de strings: ${#arrayStrings[*]}"echo "Longitud del array mixto: ${#arrayMixto[*]}"echo "Longitud del array vacío: ${#arrayVacio[*]}"echo "Longitud del array de rango: ${#arrayRango[*]}"echo -e " Añadiendo y eliminando elementos"arrayNumeros[5]=6echo "Añadiendo elemento al array de números: ${arrayNumeros[*]}"unset arrayStrings[1]echo "Eliminando elemento del array de strings: ${arrayStrings[*]}"
Overwriting scripts_bash/11_arrays.sh
!chmod +x scripts_bash/11_arrays.sh && ./scripts_bash/11_arrays.sh
ArraysArray de números: 1 2 3 4 5Array de strings: hola chao adiosArray mixto: 1 hola 2 chao 3 adiosArray vacío:Array de rango: A B C D E F G H I J K L M N O P Q R S T U V W X Y ZAccediendo a elementosPrimer elemento del array de números: 1Segundo elemento del array de strings: chaoÚltimo elemento del array de números: 5Penúltimo elemento del array de strings: chaoLongitud de arraysLongitud del array de números: 5Longitud del array de strings: 3Longitud del array mixto: 6Longitud del array vacío: 0Longitud del array de rango: 26Añadiendo y eliminando elementosAñadiendo elemento al array de números: 1 2 3 4 5 6Eliminando elemento del array de strings: hola adios
for
loop
To use the for
loop, you must use the following syntax
for `<variable>` in `<array>`
Sure, please provide the Markdown text you would like translated to English.
statement
Done
Let's see an example
%%writefile scripts_bash/12_for.sh#!/bin/basharrayNumeros=(1 2 3 4 5)arrayStrings=("hola" "chao" "adios")echo "Iterar a través de un array de numeros"for numero in ${arrayNumeros[*]}doecho "Número: $numero"doneecho -e " Iterar a través de un array de strings"for string in ${arrayStrings[*]}doecho "String: $string"doneecho -e " Iterar a través de un array no declarado"for string in "Manolo" "Juan" "Pedro"doecho "String: $string"doneecho -e " Iterar a través de un rango"for i in {1..10}doecho "Número: $i"doneecho -e " Iterar a través de un rango de manera clásica"for (( i=1; i<=10; i++ ))doecho "Número: $i"doneecho -e " Iterar a través de un comando"for file in $(ls)doecho "Archivo: $file"doneecho -e " Iterar a través de un directorio"for file in *doecho "Archivo: $file"done
Overwriting scripts_bash/12_for.sh
!chmod +x scripts_bash/12_for.sh && ./scripts_bash/12_for.sh
Iterar a través de un array de numerosNúmero: 1Número: 2Número: 3Número: 4Número: 5Iterar a través de un array de stringsString: holaString: chaoString: adiosIterar a través de un array no declaradoString: ManoloString: JuanString: PedroIterar a través de un rangoNúmero: 1Número: 2Número: 3Número: 4Número: 5Número: 6Número: 7Número: 8Número: 9Número: 10Iterar a través de un rango de manera clásicaNúmero: 1Número: 2Número: 3Número: 4Número: 5Número: 6Número: 7Número: 8Número: 9Número: 10Iterar a través de un comandoArchivo: 2021-02-11-Introduccion-a-Python.ipynbArchivo: 2021-04-23-Calculo-matricial-con-Numpy.ipynbArchivo: 2021-06-15-Manejo-de-datos-con-Pandas.ipynbArchivo: 2022-09-12-Introduccion-a-la-terminal.ipynbArchivo: 2023-01-22-Docker.ipynbArchivo: 2023-XX-XX-Bash-scripting.ipynbArchivo: california_housing_train.csvArchivo: command-line-cheat-sheet.pdfArchivo: CSS.ipynbArchivo: ExpresionesArchivo: regulares.ipynbArchivo: html_filesArchivo: html.ipynbArchivo: introduccion_pythonArchivo: mi_paquete_de_pythonArchivo: movies.csvArchivo: movies.datArchivo: notebooks_translatedArchivo: __pycache__Archivo: scripts_bashArchivo: ssh.ipynbArchivo: test.ipynbIterar a través de un directorioArchivo: 2021-02-11-Introduccion-a-Python.ipynbArchivo: 2021-04-23-Calculo-matricial-con-Numpy.ipynbArchivo: 2021-06-15-Manejo-de-datos-con-Pandas.ipynbArchivo: 2022-09-12-Introduccion-a-la-terminal.ipynbArchivo: 2023-01-22-Docker.ipynbArchivo: 2023-XX-XX-Bash-scripting.ipynbArchivo: california_housing_train.csvArchivo: command-line-cheat-sheet.pdfArchivo: CSS.ipynbArchivo: Expresiones regulares.ipynbArchivo: html_filesArchivo: html.ipynbArchivo: introduccion_pythonArchivo: mi_paquete_de_pythonArchivo: movies.csvArchivo: movies.datArchivo: notebooks_translatedArchivo: __pycache__Archivo: scripts_bashArchivo: ssh.ipynbArchivo: test.ipynb
while
Loop
To use the while
loop, you must use the following syntax
while <condition>
Sure, please provide the Markdown text you would like translated to English.
statement
Understood. Please provide the Markdown text you would like translated to English.
Let's see an example
%%writefile scripts_bash/13_while.sh#!/bin/bashnumero=1while [ $numero -ne 5 ]doecho "Número: $numero"numero=$(( numero + 1 ))done
Overwriting scripts_bash/13_while.sh
!chmod +x scripts_bash/13_while.sh && ./scripts_bash/13_while.sh
Número: 1Número: 2Número: 3Número: 4
Flow control with break
and continue
We can control the flow of a loop using the words break
and continue
, let's see an example
%%writefile scripts_bash/14_control_de_flujo.sh#!/bin/bashnumero=1while [ $numero -ne 10 ]doif [ $numero -eq 5 ]; thennumero=$(( numero + 1 ))echo "Saltando el número 5"continueelif[ $numero -eq 8 ]; thenecho "Terminando el bucle"breakfiecho "Número: $numero"numero=$(( numero + 1 ))done
Overwriting scripts_bash/14_control_de_flujo.sh
!chmod +x scripts_bash/14_control_de_flujo.sh && ./scripts_bash/14_control_de_flujo.sh
Número: 1Número: 2Número: 3Número: 4Saltando el número 5Número: 6Número: 7Terminando el bucle
Functions
The syntax for writing functions is
``` bash
statements
}```
Let's see an example
%%writefile scripts_bash/15_funciones.sh#!/bin/bashfuncion () {echo "Soy una función"}funcoionConParametros () {echo "Soy una función con parámetros"echo "Parámetro 1: $1"echo "Parámetro 2: $2"}funcionfuncoionConParametros "Hola" "Adiós"
Writing scripts_bash/15_funciones.sh
!chmod +x scripts_bash/15_funciones.sh && ./scripts_bash/15_funciones.sh
Soy una funciónSoy una función con parámetrosParámetro 1: HolaParámetro 2: Adiós