Best practices to create a Shell Script in GNU / Linux - Part 2

First of all, before reading this publication, I recommend you read the part I of said publication, called «Best practices to create a Shell Script in GNU / Linux«.

Shell scripting

Next, a small summary of the most important of happiness previous post:

A) The ideal Shebang it should be written as follows:

#! / usr / bin / env bash.

Note: Replacing the word bash by the shell of your choice.

B) To achieve an excellent STRICT or SAFE BASH MODE (Bash Strict Mode / BSM) we offer the following alternatives:

B.1) Configuration of the Debugging Section:

  1. set -o raised
  2. set -o nounset
  3. set -o pipefail
  4. # set -o xtrace

However, in this new entry we suggest in order to minimize the lines of code the following BASH STRICT or SAFE MODE (Bash Strict Mode / BSM):

set -eou pipefail

With these BSM we achieve exactly the same as with the previous 3 lines.

My personal recommendation is: Once your Shell Script is built, add the BSM line (s) to start debugging and perfecting your Script and making it highly functional. When you want, add said BSM the option (-x) to achieve the same effect as when you enable the line: set -o xtrace, in the above method, that is, your line of BSM it should look like this:

set -eoux pipefail

B.2) Configuration of the Output Section of the configured Variables:

IFS=$'\n\t'

Adding this line we proceed to reconfigure the variable Internal Field Separator and achieve a better visualization and / or capture of the words (fields) of a character string. Enable it or not, according to your requirements and needs.

With these typical settings:


    #!/bin/bash
    IFS=$' '
    items="a b c"
    for x in $items; do
        echo "$x"
    done

    IFS=$'\n'
    for y in $items; do
        echo "$y"
    done

The outputs of the variables would be obtained in the following way:


a
b
c
a b c

With the default and recommended settings:


    #!/bin/bash
    names=(
      "Aaron Maxwell"
      "Wayne Gretzky"
      "David Beckham"
      "Anderson da Silva"
    )

    echo "Con el valor por defecto de la variable IFS..."
    for name in ${names[@]}; do
      echo "$name"
    done

    echo ""
    echo "Con el Modo BSM para el valor de la variable IFS activado..."
    IFS=$'\n\t'
    for name in ${names[@]}; do
      echo "$name"
    done

The outputs of the variables would be obtained in the following way:


Con el valor por defecto de la variable IFS...
Aaron
Maxwell
Wayne
Gretzky
David
Beckham
Anderson
da
Silva

Con el Modo BSM para el valor de la variable IFS activado...
Aaron Maxwell
Wayne Gretzky
David Beckham
Anderson da Silva

B.3) Configuration Section of the default configuration of the execution terminal:

setterm --reset

Adding this line we proceed to completely reset the entire session and the execution parameters of the terminal where the use of the Shell script executed. Enable it or not, according to your requirements and needs.

With this we will have a BSM very useful and efficient to have an excellent Shell script.

Finally, we will explore what that Shell Script should have below:

  • An informative section about the Creator and the Program:

###########################################################
# SECCIÓN INFORMATIVA SOBRE EL CREADOR Y EL PROGRAMA
###########################################################

###########################################################
#                             MI PAÍS 
#
# NOMBRE: 
# VERSIÓN: 
# TIPO DE PROGRAMA:
# FUNCIÓN:
# NOMBRE CÓDIGO:
# PAÍS ORIGEN:
# CREADO POR:
# EMAIL:
# NOMBRE FACEBOOK:
# PAGINA PERSONAL FACEBOOK:
# COMUNIDAD FACEBOOK:
# TWITTER:
# TELÉFONO:
# PROMOCIONADO POR:
# PAGINA WEB DEL PROYECTO TIC - TAC:
# FECHA DE LANZAMIENTO DE LA PRIMERA VERSIÓN (1.0):
# FECHA DE LANZAMIENTO DE LA VERSIÓN ACTUAL (8.0+0):
# FECHA DE ULTIMA ACTUALIZACIÓN:
###########################################################

  • An informative section on the Licensing of the Program:

###########################################################
# SECCIÓN INFORMATIVA SOBRE EL LICENCIAMIENTO DEL PROGRAMA
###########################################################

###########################################################
# NOMBRE DEL SCRIPT DE SHELL
###########################################################
#
# Derechos de autor:
# Copyleft (C) Año - Creador
# 
# Licenciamiento:
#
# El NOMBRE DEL SCRIPT DE SHELL no viene con ninguna garantía. El 
# Autor no se hace responsable si se al aplicarse el S.O., se
# corrompe, daña o inutiliza.
#
# El NOMBRE DEL SCRIPT DE SHELL es una aplicación de Software 
# Libre, por lo tanto usted puede redistribuirlo y / o modificarlo 
# bajo los términos de la Licencia Pública General de GNU
# publicada por la free Software Foundation, o sea, la versión 3
# ó versión posterior, según sea su preferencia.
#
# Este programa se distribuye con la esperanza de que sea útil,
# pero SIN NINGUNA GARANTÍA, incluso sin la garantía implícita de
# COMERCIALIZACIÓN o IDONEIDAD para un propósito particular.
# Vea la Licencia Publica General para más detalles.
#
# Procure obtener una copia de la Licencia Pública General de GNU
# para estar al tanto sobre lo estipulado por la misma.
#
# Consúltela en:
#
# http://www.gnu.org/licenses/licenses.es.html
# http://www.gnu.org/licenses/license-list.html
# http://www.gnu.org/licenses/gpl-howto.es.html
# http://www.gnu.org/help/evaluation.html
# http://www.gnu.org/licenses/gpl-3.0.html#howto
#
# Más Información:
#
# http://www.creativecommonsvenezuela.org.ve/cc-licencias
# http://creativecommons.org/choose/?lang=es_ES
#
# Por lo tanto, Si usted hace alguna modificación en esta
# aplicación o toma una porción de él, deberá siempre mencionar al
# autor original de la misma:
#
# Desarrollador : 
# Nick          : 
# Twitter       : 
# Facebook      : 
# Telegram      : 
# Canal Telegram:
#
# Este SCRIPT tiene como propósito:
#
# 1.- PROPÓSITO 1: ABCDEFGHIJKLMNÑOPQRSTUVXYZ
#
# 2.- PROPÓSITO 2: ABCDEFGHIJKLMNÑOPQRSTUVXYZ
#
############################################################
# NOMBRE DEL SCRIPT DE SHELL
############################################################

I hope that with this second part of the "Best practices to create a Shell Script in GNU / Linux" is enough for them to be able to focus thoroughly on every little aspect of it and the reason for many things when creating a Shell scriptI mean, I hope that some of these tips will help you to make better Shell script, but not so much for yourself, but for those Users o Sysadmin you have to manage them. So that you don't have to go through a tedious and difficult task de find out what they coded, how and why, and why it no longer works.

Until the next posts on Shell Scripting!


Be the first to comment

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.