Bash scripting

Bash scripting Bash scripting

Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.

Folder with scriptslink image 18

To create this post, we are going to create a folder where we will save all the scripts

	
!mkdir scripts_bash
Copy

First scriptlink image 19

Execution binary specificationlink image 20

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 scriptslink image 21

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 varias
lineas
'
echo "Hola mundo"
Copy
	
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
Copy
	
Hola mundo

Variable declarationlink image 22

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/bash
opcion=1
nombre="Juan"
echo "Opcion: $opcion"
echo "Nombre: $nombre"
Copy
	
Writing scripts_bash/02_variables.sh
	
!chmod +x scripts_bash/02_variables.sh && ./scripts_bash/02_variables.sh
Copy
	
Opcion: 1
Nombre: Juan

Scope of variables

Variables created are only accessible from the script, that is, their scope is within the script.

Exporting Variableslink image 23

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/bash
opcion=1
nombre="Juan"
echo "Opcion: $opcion"
echo "Nombre: $nombre"
# Exportar variable nombre
echo "export nombre=$nombre"
export nombre
# Ejecutar script de importacion
echo ""
echo "Ejecutando script de importacion"
./scripts_bash/02_variables_importacion.sh
Copy
	
Overwriting scripts_bash/02_variables.sh
	
%%writefile scripts_bash/02_variables_importacion.sh
#!/bin/bash
echo "Nombre importado: $nombre"
Copy
	
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
Copy
	
Opcion: 1
Nombre: Juan
export nombre=Juan
Ejecutando script de importacion
Nombre 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
Copy
	
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 operatorslink image 24

Below, we show all possible operators

	
%%writefile scripts_bash/03_operadores.sh
#!/bin/bash
# Asignación de variables
x=10
y=20
echo "x = $x"
echo "y = $y"
# Operadores aritméticos
echo ""
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ón
echo ""
echo "Operadores de comparación"
if [ "$x" -eq "$y" ]; then
echo "x es igual a y"
else
echo "x no es igual a y"
fi
if [ "$x" -ne "$y" ]; then
echo "x no es igual a y"
else
echo "x es igual a y"
fi
if [ "$x" -lt "$y" ]; then
echo "x es menor que y"
else
echo "x no es menor que y"
fi
if [ "$x" -gt "$y" ]; then
echo "x es mayor que y"
else
echo "x no es mayor que y"
fi
# Operadores de cadena
echo ""
echo "Operadores de cadena"
if [ "$a" = "$b" ]; then
echo "a es igual a b"
else
echo "a no es igual a b"
fi
if [ "$a" != "$b" ]; then
echo "a no es igual a b"
else
echo "a es igual a b"
fi
if [ -z "$a" ]; then
echo "a es una cadena vacía"
else
echo "a no es una cadena vacía"
fi
if [ -n "$a" ]; then
echo "a no es una cadena vacía"
else
echo "a es una cadena vacía"
fi
# Operadores de archivo
echo ""
echo "Operadores de archivo"
if [ -e "/path/to/file" ]; then
echo "El archivo existe"
else
echo "El archivo no existe"
fi
if [ -f "/path/to/file" ]; then
echo "Es un archivo regular"
else
echo "No es un archivo regular"
fi
if [ -d "/path/to/dir" ]; then
echo "Es un directorio"
else
echo "No es un directorio"
fi
Copy
	
Overwriting scripts_bash/03_operadores.sh
	
!chmod +x scripts_bash/03_operadores.sh && ./scripts_bash/03_operadores.sh
Copy
	
x = 10
y = 20
Operadores aritméticos
x + y = 30
x - y = -10
x * y = 200
x / y = 0
x % y = 10
Operadores de comparación
x no es igual a y
x no es igual a y
x es menor que y
x no es mayor que y
Operadores de cadena
a es igual a b
a es igual a b
a es una cadena vacía
a es una cadena vacía
Operadores de archivo
El archivo no existe
No es un archivo regular
No es un directorio

Passing Argumentslink image 25

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 ${/string to be replaced/new string}, meaning that if we have ${1/hola/hello} it will replace the word hola with the word hello in argument 1
  • However, if we use ${/#string to be replaced/new string}, it will only replace the string in the argument if the argument starts with that string.
	
%%writefile scripts_bash/04_argumentos.sh
#!/bin/bash
# Pasos de argumentos simples
echo "Primer argumento: $1"
echo "Segundo argumento: $2"
echo "Tercer argumento: $3"
# Accediendo a todos los argumentos
echo "Todos los argumentos: $*"
# Accediendo al número de argumentos
echo "Número de argumentos: $#"
# Accediendo al nombre del script
echo "Nombre del script: $0"
# Accediendo al código de salida del último comando ejecutado
echo "Código de salida del último comando: $?"
# Accediendo al PID del script
echo "PID del script: $$"
# Accediendo a los argumentos con índices
echo "Argumento 3: ${3}"
echo "Argumento 2: ${2}"
# Accediendo a los argumentos con índices y longitud máxima
echo "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áxima
echo "Reemplazando argumento 3: ${3/arg/ARG}"
echo "Reemplazando argumento 2: $ {2/arg/ARG}"
# Accediendo a los argumentos con índices y patrones de reemplazo
echo "Reemplazando patrón en argumento 3: ${3/#tercer/TERCER}"
echo "Reemplazando patrón en argumento 2: ${2/#arg/ARG}"
Copy
	
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"
Copy
	
Primer argumento: primer argumento
Segundo argumento: segundo argumento
Tercer argumento: tercer argumento
Todos los argumentos: primer argumento segundo argumento tercer argumento
Número de argumentos: 3
Nombre del script: ./scripts_bash/04_argumentos.sh
Código de salida del último comando: 0
PID del script: 11644
Argumento 3: tercer argumento
Argumento 2: segundo argumento
Argumento 3 con longitud máxima de 2 caracteres: te
Argumento 2 con longitud máxima de 3 caracteres: seg
Reemplazando argumento 3: tercer ARGumento
Reemplazando argumento 2: segundo ARGumento
Reemplazando patrón en argumento 3: tercer argumento
Reemplazando patrón en argumento 2: segundo argumento

Running commands and saving them to a variablelink image 26

We have two ways to run a command and save its output to a variable

  • By using variable=command* By using variable=$(command)
	
%%writefile scripts_bash/05_variables_comandos.sh
#!/bin/bash
path=$(pwd)
infokernel=`uname -a`
echo "El directorio actual es: $path"
echo "La información del kernel es: $infokernel"
Copy
	
Overwriting scripts_bash/05_variables_comandos.sh
	
!chmod +x scripts_bash/05_variables_comandos.sh && ./scripts_bash/05_variables_comandos.sh
Copy
	
El directorio actual es: /home/wallabot/Documentos/web/portafolio/posts
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

Debugginglink image 27

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
Copy
	
#!/bin/bash
path=$(pwd)
infokernel=`uname -a`
echo "El directorio actual es: $path"
El directorio actual es: /home/wallabot/Documentos/web/portafolio/posts
echo "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
Copy
	
++ 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 informationlink image 28

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 the echo. 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 variable REPLY. If you want the variable where the user's input is stored to have a different name, you should use read [variable], for example, the command read myVariable will store the user's input in the variable myVariable.
  • By using the command $REPLY or $(variable) we access the data entered by the user.
	
%%writefile scripts_bash/06_leer_informacion.sh
#!/bin/bash
option=0
backupName=""
echo "Programa de utilidades"
echo -n "Ingresar una opción: "
read
option=$REPLY
echo ""
echo -n "Ingresar un nombre: "
read backupName
echo ""
echo "Opción: $option, backupName: $backupName"
Copy
	
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
Copy
	
Programa de utilidades
Ingresar 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/bash
option=0
backupName=""
echo "Programa de utilidades"
echo -n "Ingresar una opción: "
read
option1=$REPLY
echo ""
echo -n "Ingresar un nombre: "
read backupName
echo ""
read -p "Ingresar otra opción: " option2
echo ""
echo "Opción: $option1-$option2, backupName: $backupName"
Copy
	
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
Copy
	
Programa de utilidades
Ingresar una opción:
Ingresar un nombre:
Opción: 1-2, backupName: nombreprueba

Validate the user informationlink image 29

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/bash
option=0
backupName=""
echo "Programa de utilidades"
echo -n "Ingresar una opción: "
read -n1
option1=$REPLY
echo ""
echo -n "Ingresar un nombre: "
read -n4 backupName
echo ""
read -p "Ingresar otra opción: " option2
echo ""
echo "Opción: $option1-$option2, backupName: $backupName"
Copy
	
Writing scripts_bash/07_validar_informacion.sh
	
!chmod +x scripts_bash/07_validar_informacion.sh && echo "1back2" | ./scripts_bash/07_validar_informacion.sh
Copy
	
Programa de utilidades
Ingresar 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/bash
option=0
backupName=""
echo "Programa de utilidades"
echo -n "Ingresar una opción: "
read -n1
option1=$REPLY
echo ""
echo -n "Ingresar un nombre: "
read -n4 backupName
echo ""
read -p "Ingresar otra opción: " option2
echo ""
read -s -p "Password: " password
echo ""
echo "Opción: $option1-$option2, backupName: $backupName, password: $password"
Copy
	
Overwriting scripts_bash/07_validar_informacion.sh
	
!chmod +x scripts_bash/07_validar_informacion.sh && echo "1back2 1234" | ./scripts_bash/07_validar_informacion.sh
Copy
	
Programa de utilidades
Ingresar una opción:
Ingresar un nombre:
Opción: 1-2, backupName: back, password: 1234

If elselink image 30

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/bash
if [[ 1 &gt; 2 ]]; then
echo "Verdadero"
elif [[ 1 &gt; 3 ]]; then
echo "Verdadero"
else
echo "Falso"
fi
Copy
	
Overwriting scripts_bash/08_if_else.sh
	
!chmod +x scripts_bash/08_if_else.sh && ./scripts_bash/08_if_else.sh
Copy
	
Falso

Let's see how nested ifs are created

	
%%writefile scripts_bash/08_if_else.sh
#!/bin/bash
if [[ 1 &gt; 2 ]]; then
echo "Verdadero"
elif [[ 1 &gt; 3 ]]; then
echo "Verdadero"
else
if [[ 1 &gt; 4 ]]; then
echo "Verdadero pero falso"
else
echo "Totalmente falso"
fi
fi
Copy
	
Overwriting scripts_bash/08_if_else.sh
	
!chmod +x scripts_bash/08_if_else.sh && ./scripts_bash/08_if_else.sh
Copy
	
Totalmente falso

Conditional expressionslink image 31

We have already seen how to create ifs, 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` [[ -nt ]]
Is file1 older than file2? `-ot` [[ -ot ]]
Is file1 the same as file2? `-ef` [[ -ef ]]
Is file1 the same as file2? `-ef` [[ -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/bash
echo "Comparando strings"
string1="hola"
string2="hola"
string3="chao"
string4=""
if [[ $string1 &gt; $string3 ]]; then
echo "$string1 es mayor que $string3"
fi
if [[ $string3 &lt; $string1 ]]; then
echo "$string3 es menor que $string1"
fi
if [[ $string1 == $string2 ]]; then
echo "$string1 es igual que $string2"
fi
if [[ $string1 != $string3 ]]; then
echo "$string1 es diferente que $string3"
fi
if [[ -z $string4 ]]; then
echo "$string4 es una cadena vacía"
fi
if [[ -n $string3 ]]; then
echo "$string3 es una cadena no vacía"
fi
if [[ $string3 ]]; then
echo "$string3 es una cadena no vacía"
fi
echo -e " Comparando números"
number1=10
number2=10
number3=20
if [[ $number3 -gt $number1 ]]; then
echo "$number3 es mayor que $number1"
fi
if [[ $number3 -ge $number2 ]]; then
echo "$number3 es mayor o igual que $number2"
fi
if [[ $number1 -lt $number3 ]]; then
echo "$number1 es menor que $number3"
fi
if [[ $number1 -le $number2 ]]; then
echo "$number1 es menor o igual que $number2"
fi
if [[ $number1 -eq $number2 ]]; then
echo "$number1 es igual que $number2"
fi
if [[ $number1 -ne $number3 ]]; then
echo "$number1 es diferente que $number3"
fi
echo -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 ]]; then
echo "$file2 es un directorio"
fi
if [[ -f $file1 ]]; then
echo "$file1 es un archivo"
fi
if [[ -e $file1 ]]; then
echo "$file1 existe"
fi
if [[ -r $file1 ]]; then
echo "$file1 es legible"
fi
if [[ -w $file1 ]]; then
echo "$file1 es escribible"
fi
if [[ -x $file1 ]]; then
echo "$file1 es ejecutable"
fi
if [[ -L $file1 ]]; then
echo "$file1 es un link"
fi
if [[ -s $file1 ]]; then
echo "$file1 tiene contenido"
fi
if [[ -O $file1 ]]; then
echo "$file1 es propiedad del usuario"
fi
if [[ -G $file1 ]]; then
echo "$file1 es propiedad del grupo"
fi
if [[ -N $file1 ]]; then
echo "$file1 fue modificado"
fi
if [[ $file1 -nt $file2 ]]; then
echo "$file1 es más nuevo que $file2"
fi
if [[ $file1 -ot $file2 ]]; then
echo "$file1 es más viejo que $file2"
fi
if [[ $file1 -ef $file1 ]]; then
echo "$file1 es el mismo archivo que $file2"
fi
echo -e " Comparando expresiones con AND"
if [[ 2 &gt; 1 && 3 &gt; 1 ]]; then
echo "2 &gt; 1 y 3 &gt; 1"
fi
echo -e " Comparando expresiones con OR"
if [[ 2 &gt; 1 || 1 &gt; 2 ]]; then
echo "2 &gt; 1 o 1 &gt; 2"
fi
echo -e " Comparando expresiones con NOT"
if [[ ! 1 &gt; 2 ]]; then
echo "1 &gt; 2 no es cierto"
fi
Copy
	
Overwriting scripts_bash/09_condicionales.sh
	
!chmod +x scripts_bash/09_condicionales.sh && ./scripts_bash/09_condicionales.sh
Copy
	
Comparando strings
hola es mayor que chao
chao es menor que hola
hola es igual que hola
hola es diferente que chao
es una cadena vacía
chao es una cadena no vacía
chao es una cadena no vacía
Comparando números
20 es mayor que 10
20 es mayor o igual que 10
10 es menor que 20
10 es menor o igual que 10
10 es igual que 10
10 es diferente que 20
Comparando 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_bash
Comparando expresiones con AND
2 &gt; 1 y 3 &gt; 1
Comparando expresiones con OR
2 &gt; 1 o 1 &gt; 2
Comparando expresiones con NOT
1 &gt; 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/bash
variable="amarillo"
case $variable in
"rojo") echo "Color rojo";;
"verde") echo "Color verde";;
"azul") echo "Color azul";;
*) echo "Color desconocido";;
esac
Copy
	
Writing scripts_bash/10_case.sh
	
!chmod +x scripts_bash/10_case.sh && ./scripts_bash/10_case.sh
Copy
	
Color desconocido

Arrayslink image 32

Let's see how arrays behave in bash scripting

	
%%writefile scripts_bash/11_arrays.sh
#!/bin/bash
arrayNumeros=(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]=6
echo "Añadiendo elemento al array de números: ${arrayNumeros[*]}"
unset arrayStrings[1]
echo "Eliminando elemento del array de strings: ${arrayStrings[*]}"
Copy
	
Overwriting scripts_bash/11_arrays.sh
	
!chmod +x scripts_bash/11_arrays.sh && ./scripts_bash/11_arrays.sh
Copy
	
Arrays
Array de números: 1 2 3 4 5
Array de strings: hola chao adios
Array mixto: 1 hola 2 chao 3 adios
Array 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 Z
Accediendo a elementos
Primer elemento del array de números: 1
Segundo elemento del array de strings: chao
Último elemento del array de números: 5
Penúltimo elemento del array de strings: chao
Longitud de arrays
Longitud del array de números: 5
Longitud del array de strings: 3
Longitud del array mixto: 6
Longitud del array vacío: 0
Longitud del array de rango: 26
Añadiendo y eliminando elementos
Añadiendo elemento al array de números: 1 2 3 4 5 6
Eliminando 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/bash
arrayNumeros=(1 2 3 4 5)
arrayStrings=("hola" "chao" "adios")
echo "Iterar a través de un array de numeros"
for numero in ${arrayNumeros[*]}
do
echo "Número: $numero"
done
echo -e " Iterar a través de un array de strings"
for string in ${arrayStrings[*]}
do
echo "String: $string"
done
echo -e " Iterar a través de un array no declarado"
for string in "Manolo" "Juan" "Pedro"
do
echo "String: $string"
done
echo -e " Iterar a través de un rango"
for i in {1..10}
do
echo "Número: $i"
done
echo -e " Iterar a través de un rango de manera clásica"
for (( i=1; i&lt;=10; i++ ))
do
echo "Número: $i"
done
echo -e " Iterar a través de un comando"
for file in $(ls)
do
echo "Archivo: $file"
done
echo -e " Iterar a través de un directorio"
for file in *
do
echo "Archivo: $file"
done
Copy
	
Overwriting scripts_bash/12_for.sh
	
!chmod +x scripts_bash/12_for.sh && ./scripts_bash/12_for.sh
Copy
	
Iterar a través de un array de numeros
Número: 1
Número: 2
Número: 3
Número: 4
Número: 5
Iterar a través de un array de strings
String: hola
String: chao
String: adios
Iterar a través de un array no declarado
String: Manolo
String: Juan
String: Pedro
Iterar a través de un rango
Número: 1
Número: 2
Número: 3
Número: 4
Número: 5
Número: 6
Número: 7
Número: 8
Número: 9
Número: 10
Iterar a través de un rango de manera clásica
Número: 1
Número: 2
Número: 3
Número: 4
Número: 5
Número: 6
Número: 7
Número: 8
Número: 9
Número: 10
Iterar a través de un comando
Archivo: 2021-02-11-Introduccion-a-Python.ipynb
Archivo: 2021-04-23-Calculo-matricial-con-Numpy.ipynb
Archivo: 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
Archivo: 2022-09-12-Introduccion-a-la-terminal.ipynb
Archivo: 2023-01-22-Docker.ipynb
Archivo: 2023-XX-XX-Bash-scripting.ipynb
Archivo: california_housing_train.csv
Archivo: command-line-cheat-sheet.pdf
Archivo: CSS.ipynb
Archivo: Expresiones
Archivo: regulares.ipynb
Archivo: html_files
Archivo: html.ipynb
Archivo: introduccion_python
Archivo: mi_paquete_de_python
Archivo: movies.csv
Archivo: movies.dat
Archivo: notebooks_translated
Archivo: __pycache__
Archivo: scripts_bash
Archivo: ssh.ipynb
Archivo: test.ipynb
Iterar a través de un directorio
Archivo: 2021-02-11-Introduccion-a-Python.ipynb
Archivo: 2021-04-23-Calculo-matricial-con-Numpy.ipynb
Archivo: 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
Archivo: 2022-09-12-Introduccion-a-la-terminal.ipynb
Archivo: 2023-01-22-Docker.ipynb
Archivo: 2023-XX-XX-Bash-scripting.ipynb
Archivo: california_housing_train.csv
Archivo: command-line-cheat-sheet.pdf
Archivo: CSS.ipynb
Archivo: Expresiones regulares.ipynb
Archivo: html_files
Archivo: html.ipynb
Archivo: introduccion_python
Archivo: mi_paquete_de_python
Archivo: movies.csv
Archivo: movies.dat
Archivo: notebooks_translated
Archivo: __pycache__
Archivo: scripts_bash
Archivo: ssh.ipynb
Archivo: 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/bash
numero=1
while [ $numero -ne 5 ]
do
echo "Número: $numero"
numero=$(( numero + 1 ))
done
Copy
	
Overwriting scripts_bash/13_while.sh
	
!chmod +x scripts_bash/13_while.sh && ./scripts_bash/13_while.sh
Copy
	
Número: 1
Número: 2
Número: 3
Nú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/bash
numero=1
while [ $numero -ne 10 ]
do
if [ $numero -eq 5 ]; then
numero=$(( numero + 1 ))
echo "Saltando el número 5"
continue
elif
[ $numero -eq 8 ]; then
echo "Terminando el bucle"
break
fi
echo "Número: $numero"
numero=$(( numero + 1 ))
done
Copy
	
Overwriting scripts_bash/14_control_de_flujo.sh
	
!chmod +x scripts_bash/14_control_de_flujo.sh && ./scripts_bash/14_control_de_flujo.sh
Copy
	
Número: 1
Número: 2
Número: 3
Número: 4
Saltando el número 5
Número: 6
Número: 7
Terminando el bucle

Functionslink image 33

The syntax for writing functions is

``` bash

()

statements

}```

Let's see an example

	
%%writefile scripts_bash/15_funciones.sh
#!/bin/bash
funcion () {
echo "Soy una función"
}
funcoionConParametros () {
echo "Soy una función con parámetros"
echo "Parámetro 1: $1"
echo "Parámetro 2: $2"
}
funcion
funcoionConParametros "Hola" "Adiós"
Copy
	
Writing scripts_bash/15_funciones.sh
	
!chmod +x scripts_bash/15_funciones.sh && ./scripts_bash/15_funciones.sh
Copy
	
Soy una función
Soy una función con parámetros
Parámetro 1: Hola
Parámetro 2: Adiós

Continue reading

Last posts -->

Have you seen these projects?

Horeca chatbot

Horeca chatbot Horeca chatbot
Python
LangChain
PostgreSQL
PGVector
React
Kubernetes
Docker
GitHub Actions

Chatbot conversational for cooks of hotels and restaurants. A cook, kitchen manager or room service of a hotel or restaurant can talk to the chatbot to get information about recipes and menus. But it also implements agents, with which it can edit or create new recipes or menus

Subtify

Subtify Subtify
Python
Whisper
Spaces

Subtitle generator for videos in the language you want. Also, it puts a different color subtitle to each person

View all projects -->

Do you want to apply AI in your project? Contact me!

Do you want to improve with these tips?

Last tips -->

Use this locally

Hugging Face spaces allow us to run models with very simple demos, but what if the demo breaks? Or if the user deletes it? That's why I've created docker containers with some interesting spaces, to be able to use them locally, whatever happens. In fact, if you click on any project view button, it may take you to a space that doesn't work.

Flow edit

Flow edit Flow edit

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
View all containers -->

Do you want to apply AI in your project? Contact me!

Do you want to train your model with these datasets?

short-jokes-dataset

Dataset with jokes in English

opus100

Dataset with translations from English to Spanish

netflix_titles

Dataset with Netflix movies and series

View more datasets -->