Build your program step by step using Shell Scripting - Part 2

In the part 1 from this series we remember about how to implement a:

And in previous ones, we soaked ourselves in the better practices to follow when creating an excellent Shell script in Bash for Linux, and very specifically in terms of designing a Shebang and a BSM (Bash Strict Mode / Strict Bash Mode).

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

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

Shell scripting

In this post we will see how to implement a Environment Variables Module for a Shell Script in Bash for Linux, taking as an example one of my programs (applications) facts in a Shell script called Linux Post Install - Bicentennial Script 8.0, but first a small summary of the better practices so that you keep them in mind:

  • Indente your code,
  • Add separation spaces between sections of code,
  • Comment as much as you can on the code,
  • Create variables with descriptive names of their functions,
  • Use the syntax VARIABLE = $ (command) for command substitution
  • Use modules and / or variables of: Superuser and Authorized User Validation with or without established passwords.
  • Use modules and / or variables of: Validation of the Operating System (Distro, Version, Architecture, among others.),
  • Use modules (procedures / sections) to confirm the execution of critical or batch actions (activities / functions),
  • Provide User Friendly Interfaces (Userfriendly): By Terminal (with Menus and Colors using Dialog) and / or By Desktop (with Windows using Zenity and Gxmessage),
  • Include modules of Welcome and Farewell (messages) to the user, if necessary,
  • Include a double run verification module,
  • Rationalize the script size with External Functions and / or Modules,
  • Invoke in a clear and evident way the calls to other Interpreters,
  • Apply any other logical and rational recommendation that you consider necessary.

Here is an example of a Environment Variables Module for a Shell Script in Bash for Linux. This should be the module (section) that contains all those certain or probable variables that the Shell script needs or will need for its execution. I personally add the following:


###############################################################################
# INICIO DEL MODULO DE VARIABLES DE ENTORNO DEL SCRIPT
###############################################################################

NOM_SCRIPT=lpi_sb8_inicio_2016.sh
# echo $NOM_SCRIPT
# Almacenar como una variable predeterminada el Nombre real del Script

USR1_VALID=sysadmin
# echo $USR1_VALID
# Almacenar como una variable predeterminada el Nombre de Usuario valido que podrá ejecutar el Script.
# Haga una variable por cada Usuario Autorizado.

PASSWD_VALID=lpi*sb8
# echo $PASSWD_VALID
# Almacenar como una variable predeterminada el Nombre de la contraseña valida que permitirá ejecutar el Script.
# Haga una variable por cada contraseña de cada Usuario Autorizado.

S_O_VALID=kali
# echo $S_O_VALID
# Almacenar como una variable predeterminada el tipo de Sistema operativo valido para donde debe ser ejecutado el Script.

HOST_VALID=hostmovil-sysadmin
# echo $HOST_VALID
# Almacenar como una variable predeterminada el nombre del host valido donde debe ser ejecutado el Script.

IP_VALID=192.168.1.107
# echo $IP_VALID
# Almacenar como una variable predeterminada el nombre del host valido donde debe ser ejecutado el Script.

MAC_VALID=44:8a:5b:f0:3d:f3
# echo $MAC_VALID
# Almacenar como una variable predeterminada el nombre del host valido donde debe ser ejecutado el Script.

FILE_LOCK=lpi_sb_file_lock.txt
# echo $FILE_LOCK
# Almacenar el nombre de archivo predeterminada por el sistema para evitar doble ejecuciones ó detectar ejecuciones fallidas.

IDSUPERUSER=$(id -u | awk '{print $1}')
# IDSUPERUSER=$(echo $UID)
# IDSUPERUSER=$(getent passwd $USER | cut -d: -f3)
# echo $IDSUPERUSER
# Almacenar IUD del Superusuario root

USER_NAME_1=$(cat /etc/passwd | grep 1000 | cut -d: -f1 | awk '{print $1}')
HOME_USER_NAME_1=/home/$USER_NAME_1
# echo $USER_NAME_1 $HOME_USER_NAME_1
# Almacenar el nombre del usuario 1000 y su /home. Probable unico y primer Usuario del Sistema.

USER_NAME_2=$(cat /etc/passwd | grep 1001 | cut -d: -f1 | sed -n '2p' | awk '{print $1}')
HOME_USER_NAME_2=/home/$USER_NAME_2
# echo $USER_NAME_2 $HOME_USER_NAME_2
# Almacenar el nombre del usuario 1001 y su /home. Probable segundo Usuario del Sistema.

ID_USERNAME_SESSION=$(for i in $(who | sed 1q | cut -c 1-8); do grep $i /etc/passwd | awk '{print "\t" $1}' | tr -d '[A-Za-z]' | sed 's/::x*//' | cut -c 1-5 | awk '{print $1}' ; done | sed 1q)
# echo $ID_USERNAME_SESSION
# Almacenar el ID del Nombre del primer usuario (alfabeticamente) detectado conectado (con sesión abierta) en el sistema.

USERNAME_ID_SESSION=$(for i in $(who | sed 1q | cut -c 1-8); do grep $i /etc/passwd | awk '{print "\t" $1}' | tr -d '[A-Za-z]' | sed 's/::x*//' | cut -c 1-5 | awk '{print $2}' ; done ; echo $i)
# echo $USERNAME_ID_SESSION
# Almacenar el Nombre del primer usuario (alfabeticamente) detectado conectado (con sesión abierta) en el sistema.

# ID_FIRST_USERNAME=$(for i in 1000 1001 1002 1003 1004; do grep $i /etc/passwd | awk '{print "\t" $1}' | tr -d '[A-Za-z]' | sed 's/::x*//' | cut -c 1-5 | awk '{print $1}' ; done | sed -n '1p')
# echo $ID_FIRST_USERNAME
# Almacenar el ID del Nombre del primer usuario creado en el sistema entre los ID del 1000 al 1005.
# Nota: Solo funciona con la opción -o desactivada del MODO BASH ESTRICTO ó SEGURO (Bash Strict Mode / BSM)

# ID_FIRST_USERNAME=$(for i in $(seq 1000 1999); do grep $i /etc/passwd | awk '{print "\t" $1}' | tr -d '[A-Za-z]' | sed 's/::x*//' | cut -c 1-5 | awk '{print $1}' ; done | sed -n '1p')
# echo $ID_FIRST_USERNAME
# Almacenar el ID del Nombre del primer usuario creado en el sistema.
# Nota: Solo funciona con la opción -o desactivada del MODO BASH ESTRICTO ó SEGURO (Bash Strict Mode / BSM)

UBICACION=$(echo $PWD)
# UBICACION=$(pwd)
# echo $UBICACION
# Almacenar ruta de ejecución del Script LPI-SB

FECHA_SISTEMA_AN=$(date +"%d %b %y")
# echo $FECHA_SISTEMA_AN
# Almacenar la fecha  Alfanumerica actual del Equipo

FECHA_SISTEMA_N=$(date +"%d %m %y")
# echo $FECHA_SISTEMA_N
# Almacenar la fecha Numerica actual del Equipo

DIA_ACTUAL=$(date +"%d")
# echo $DIA_ACTUAL
# Almacenar el día actual del Equipo

MES_ACTUAL_A=$(date +"%b")
# echo $MES_ACTUAL_A
# Almacenar el mes alfabetico actual del Equipo

MES_ACTUAL_N=$(date +"%m")
# echo $MES_ACTUAL_N
# Almacenarel mes numerico actual del Equipo

ANO_ACTUAL_2C=$(date +"%y")
# echo $ANO_ACTUAL_2C
# Almacenar el año (con 2 cifras) actual del Equipo

ANO_ACTUAL_4C=$(date +"%Y")
# echo $ANO_ACTUAL_4C
# Almacenar el año (con 4 cifras) actual del Equipo

HORA_SISTEMA=$(date +"%H:%M")
# echo $HORA_SISTEMA
# Almacenar la Hora actual del Equipo

HORA_ACTUAL=$(date +"%H")
# echo $HORA_ACTUAL
# Almacenar la Hora actual del Equipo

MINUTOS_ACTUAL=$(date +"%M")
# echo $MINUTOS_ACTUAL
# Almacenar la Hora actual del Equipo

TIPO_S_O_L=$(uname -o)
# echo $TIPO_S_O_L
# Almacena el nombre largo del tipo de Sistema Operativo encontrado.

TIPO_S_O_C=$(uname -s)
# echo $TIPO_S_O_C
# Almacena el nombre corto del tipo de Sistema Operativo encontrado.

NOM_DISTRO_L=$(cat /etc/os-release | grep NAME | grep -v "VERSION" | sed -n '2p' | cut -f2 -d\")
# NOM_DISTRO_L=$(lsb_release -d | sed 's/Description://')
# echo $NOM_DISTRO_L
# Almacena el nombre largo de la Distro detectada.

NOM_DISTRO_C=$(cat /etc/os-release | grep NAME | grep -v "VERSION" | sed -n '2p' | cut -f2 -d\" | awk '{print $1}')
# NOM_DISTRO_C=$(lsb_release -d | sed 's/Description://' | awk '{print $1}')
# echo $NOM_DISTRO_C
# Almacena el nombre corto de la Distro detectada.

ID_DISTRO=$(cat /etc/os-release | grep ID | grep -v "VERSION_ID" | grep -v "ID_LIKE" | sed 's/ID=//' | sed 's/"//g')
# ID_DISTRO=$(lsb_release -i | awk '{print $3}')
# echo $ID_DISTRO
# Almacena el ID de la Distro detectada.

VER_DISTRO=$(cat /etc/os-release | grep VERSION= | sed -n '1p' | sed 's/VERSION=//' | sed 's/"//g')
# VER_DISTRO=$(lsb_release -c | sed 's/Codename://')
# echo $VER_DISTRO
# Almacena el nombre de la versión de la Distro detectada.

ID_VER_DISTRO=$(cat /etc/os-release | grep VERSION_ID= | sed -n '1p' | sed 's/VERSION_ID=//' | sed 's/"//g')
# ID_VER_DISTRO=$(lsb_release -r | sed 's/Release://')
# echo $ID_VER_DISTRO
# Almacena el ID de la versión de la Distro detectada.

ARQ_DISTRO_COD=$(uname -m)
# echo $ARQ_DISTRO_COD
# Almacenar el Tipo de Arquitectura de la Distro detectada en forma codificada.

ARQ_DISTRO_COD=$(uname -m) ; if [[ "$ARQ_DISTRO_COD" = "x86" ]]; then ARQ_DISTRO_HUM=32; else ARQ_DISTRO_HUM=64; fi
# echo $ARQ_DISTRO_HUM
# Convertir el Tipo de Arquitectura de la Distro detectada en forma codificada a forma humana.

VER_KERNEL=$(uname -r)
# echo $VER_KERNEL
# Almacenar el Nombre del Arquitectura de la Distro detectada.

NOM_HOST=$(cat /etc/hostname)
# echo $NOM_HOST
# Almacenar el Nombre del Host donde se ejecuta el Script.

IP_ETH0=$(ifconfig eth0 | grep inet | grep -v inet6 | cut -d ":" -f 2 | cut -d " " -f 1)
MAC_ETH0=$(ifconfig eth0 | sed -n '1p' | awk '{print $5}')
# IP_INTERNA=$(hostname -I)
# echo $IP_ETH0 $MAC_ETH0
# Almacenar la IP / MAC del Host donde se ejecuta el Script.

echo "Variables de entorno cargadas sin errores, en 5 segundos la aplicación continuará ejecutandose"
sleep 5

###############################################################################
# FINAL DEL MODULO DE VARIABLES DE ENTORNO DEL SCRIPT
###############################################################################

===============

Note: Depending on your requirements or implementations you can add the command command export my_variable below each of the previous variables created or create and export your own variables created directly with the command command export my_variable = my_parameters

Later, in future posts we will continue to see an example of modules (sections) that perform functions such as:

  • DOUBLE EXECUTION DETECTION MODULE or FAILED EXECUTION
  • OPTIMIZATION MODULE
  • USER AUTHORIZATION MODULE WITH PASSWORD
  • MODULE OF DETECTION OF THE ARCHITECTURE OF THE OPERATING SYSTEM
  • CODING LANGUAGE CONFIGURATION MODULE
  • PROXY CONFIGURATION MODULE FOR THE EXECUTION ENVIRONMENT

Among many others!

They can go self-taught about the commands: gksu, dialog, gxmessage, zenity, espeak, play, among many others to create graphical interfaces by Terminal or for the User's Desktop, with sonic or multimedia alerts, and advance knowledge that they will use later.

Remember that these and any other recommendations on some module, function, variable, command or action in general it can be carried out many ways, and what is shown here is only one simple way, Of the many possible and probable ways in which said action can or could be carried out!

Just to finish I leave you, a Screencast made by me, to show you what you would be capable of, after finishing this Shell Scripting online course in DesdeLinux:

LPI-SB8 Test ScreenCast

(LINUX POST INSTALL - BICENTENNIAL SCRIPT 8.0.0) - Part 2


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.

  1.   nameless said

    Date for humans:
    echo -e «\ e [1; 32mDate:» $ (date «+% d-% m-% Y») «\ e [1; 32m Time:» $ (date «+% T»)

    True "uname -s":
    cat / proc / sys / kernel / ostype

    Distro name:
    cat / etc / * release | cut -f2 -d »| head -1

    Hostname:
    cat / proc / sys / kernel / hostname

    OS Architecture:
    [[-x / sbin / init]] && file / sbin / init | awk '{print $ 7}' | tr -d ',' || [[-x / lib / systemd / systemd]] && file / lib / systemd / systemd | awk '{print $ 7}' | tr -d ',' 2> / dev / null

    Kernel Version:
    cat / proc / sys / kernel / osrelease

  2.   Jose Albert said

    I really liked your first contribution "date for humans" since the output would be as an example:

    Date: 11-02-2016 Time: 16:04:10

    Which effectively in a dialog, zenity or gxmessage window is very visually digestible!

    With your second suggestion I would like to place it like this:

    if true "uname -s" && cat / proc / sys / kernel / ostype; then echo "Operating system validated"; fi | thirst 1d

    And finally, thank you very much for your enriching contributions as always!