Bash automation basics and scripting (part 2)

Contents

Shutterstock / Mopic

Bash is an ideal shell and coding language, allowing you to create high-end automation scripts. In this second part of the series, we will see the encoding density, inline comments and correct quotes of variables using single or double quotes.

Bash automation basics and scripting

If you haven't already, and it's just starting in bash, lea nuestro post Bash Automation and Scripting Basics Part 1. This is the second post in our three-part series on bash automation and scripting basics. In today's post we will see, among other topics, Bash encoding density and its connection to developer preferences. We will also see the online comments in connection with this.

Once we started creating small scripts, we explore variables and work with text strings, we quickly realize that there may be a conceptual difference between single and double quotes. There is, and in the second topic below we will dive into this.

Density and Conciseness of Bash Encoding

El lenguaje de codificación Bash puede ser muy denso y conciso, pero además puede ser espacioso y detallado. Depende en gran medida de las preferencias del desarrollador.

As an example, el siguiente código Bash:

true || echo 'untrue'

Que se puede leer como No haga nada y hágalo con éxito (exit code 0), y si eso falla (puede leer el modismo Bash || como OR) muestra el texto ‘falso, además se puede escribir como:

if [ ! true ]; then
  echo 'untrue'
fi

Lo que hace que el código sea un poco distinto, pero simplemente hace lo mismo.

Esto a su vez se puede leer como Si es verdad no es (meaning by the ! idiom) true, then show the text 'false’.

Two ways to code in Bash;  same functionality, quite different code

Both mini-scripts result in the same empty output, What certain It is not fake.

The multitude of commands and tools available (or installable) from and on the command line further extend the workable scrolling between highly readable scripts and dense code, concise and difficult to understand.

While the above examples are short and relatively easy to understand, when you create a long line (a definition often used by Bash developers to indicate a code snippet, consisting of several commands, written in one line) using many of those commands , instead of putting the same in a more detailed script, the difference becomes clearer. To consider:

V ="$(sleep 2 & fg; echo -n '1' | but 's|[0-9]|a|')" && echo "${V}" | but 's|[a-z]|2|g' || echo 'fail'

A complex example of an eyeliner

This is a typical single line Bash script that uses the commands sleep, fg, echo, and sed as well as various Bash idioms and regex to simply sleep 2 seconds, generate text and transform this text using regular expressions. The script also regularly checks the conditions / Previous command results through the use of Bash idioms || (if not successful, do the following) and && (if successful, do the following)

I translated this, with fuzzy matching functionality, to a more complete script, with some modifications. As an example, we change our fg (bring the sleep command placed in the background back to the foreground, y espere a que termine como procesos normales sin segundo plano) in order to wait que esperará el PID del sueño (iniciado por eval y capturado usando el modismo Bash $!) to end.

#!/bin/bash

CMD="sleep 2"
eval ${CMD} &
wait $!
EXIT_CODE=${?}

V ="$(echo -e "${CMD}n1" | but 's|[0-9]|a|')"

if [ ${EXIT_CODE} -eq 0 ]; then
  echo "${V}" | but 's|[a-z]|2|g'
  EXIT_CODE=${?}
  if [ ${EXIT_CODE} -born 0 ]; then
    echo 'fail'
  fi
fi

Instead, el mismo complejo en línea en un script completo

What a difference! Y esto es solo one desarrollador escribiéndolo en su camino. El código Bash escrito por otros tiende a ser algo difícil de leer, y esa dificultad aumenta rápidamente con la densidad y la concisión. Even so, an expert level developer in bash will quickly understand even very dense and concise code written by others, with some exceptions, as an example, regular expressions.

For more information about writing regular expressions, have a look at How to modify text using regex with sed Stream Editor.

From these examples, it is clear that your mileage will vary over time. Despite this, in general, programmer ease of use is recommended (writing highly readable code) siempre que comience a desarrollar scripts Bash.

Si tiene que crear un código denso y conciso, puede proporcionar muchos comentarios en línea. Una línea prefijada por un # se considera una línea de comentario / observación, y el símbolo # inclusive se puede utilizar hacia el final de una línea después de cualquier comando ejecutable, para publicar un comentario de sufijo que explique el comando, conditional statement, etc. As an example:

# This code will sleep one second, twice
sleep 1  # First sleep
sleep 1  # Second sleep

¿Cotizaciones simples o cotizaciones dobles?

In bash, texto entre comillas simples (') son tomados como texto literal por el intérprete de Bash, mientras que el texto entre comillas dobles (") es interpretado (analizado) por el intérprete de Bash. Mientras que la diferencia en cómo funcionan las cosas puede no ser clara de inmediato a partir de esta definición, el siguiente ejemplo nos muestra lo que sucede cuando intercambiamos ' by " and vice versa:

echo ' $(echo "Hello world") '
echo " $(echo 'Hello world') "

Comillas simples versus comillas dobles en Bash en un ejemplo de hola mundo

In the first example, el texto $(echo "Hello world") se ve como texto literal, so the output is simply $(echo "Hello world") . Despite this, for the second example, the output is Hello world .

The Bash interpreter parsed the text in double quotes to see if it found any special Bash languages ​​to act on. One such idiom was found in $( ... ) which simply starts a sublayer and executes whatever is present between the ( ... ) idioms. Think of it as a shell within a shell, un subshell, which executes everything that happens to it as an absolutely new command. The output of any such command or commands is returned to the top-level shell and inserted in the exact place where the subshell was started.

So, our sublayer ran echo 'Hello world' of which the output is Hello world. Once this is done, the sublayer ended and the text Hello world was inserted in place of the $( ... ) sublayer invocation (think of it like all $( ... ) the code is being replaced by any output generated by the sublayer.

The result, for the upper shell, is the following command: echo " Hello world ", of which the output is Hello world as we saw.

Note that we change the double quotes inside the sublayer to single quotes. This is not necessary! One would expect to see a parse error when a command takes the syntax of echo " ... " ... " ... ", in the sense that the second double quotes would end with the first, followed by more tests and, so, would cause an error. Despite this, This is not the case.

And this is not because Bash is flexible with multiple quote strings (you accept echo 'test'"More test"'test' happily, as an example), but because the underlayer is a shell itself and, so, double quotes can be used, again, within the sublayer. Let's try this with an additional example:

echo "$(echo "$(echo "more double quotes")")"

Bash easily accepts repeated double quotes within a sublayer

This will work fine and produce the output more double quotes. The two nested sublayers (running inside the main shell you're running this from) accept, at the same time, double quotes and no errors are generated, even if multiple double quotes are nested in the general single line command. This shows some of the programming power of Bash.

In summary

Having explored the encoding density, we realize the value of writing highly readable code. However, if we have to make a dense and concise code, we can add many comments online using # for easy readability. We look at the single and double quotes and how their functionality differs substantially.

We also briefly analyze the inline comments in the scripts, as well as the functionality of the sublayer when run from a string enclosed in double quotes. In conclusion, we saw how a sublayer can use another set of double quotes without affecting the double quotes used at a higher level in any way.

En Bash Automation and Scripting Basics (Part 3), we discuss script debugging and more. to enjoy!

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.