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

As we already have seen and learned in previous entries how should we create the parts initials (upper) in our scripts, that is, the Shebang and the BSM (Bash Strict Mode).

Shell scripting

In this post we will only proceed to remember them without explaining them, as I would place it in one of my programs (applications) facts in a Shell script called Linux Post Install - Bicentennial Script 8.0:

s30a90


#!/usr/bin/env bash
# SheBang que le indica al Script que deberá usar al interprete bash ubicado en la ruta absoluta según el Sistema Operativo.

###############################################################################
# MODO BASH ESTRICTO ó SEGURO (Bash Strict Mode / BSM)
###############################################################################

###############################################################################
# SECCIÓN DE DEPURACIÓN DE ERRORES
###############################################################################
###############################################################################
set -eou pipefail
###############################################################################
# set -eou pipefail
#
# Para indicarle al script detener y cerrarse cuando:
# 1.- (-e) Un comando o linea de ejecución se ejecute y falla por completo.
# 2.- (-o) Un comando o linea de ejecución se ejecute con éxito, pero con novedad.
# 3.- (-u) Una secuencia de comandos intente utilizar variables no declaradas.
# 4.- (-x) Agréguele (Habilítelo) en caso de necesitar depurar el script.
###############################################################################
# LEER MAS EN:
# http://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
###############################################################################
# OTRAS FORMAS DE IMPLEMENTACIÓN
###############################################################################
# set -e         # Cerrar cuando un comando o linea de ejecución falle por completo.
# set -o errexit # Cerrar cuando un comando o linea de ejecución falle pero con novedad.
# set -o nounset # Cerrar cuando se intenta utilizar variables no declaradas.
# set -o xtrace  # Rastrear lo que se ejecuta. Útil para la depuración.
###############################################################################


###############################################################################
# SECCIÓN DE LA SALIDA DE LAS VARIABLES CONFIGURADAS
###############################################################################
###############################################################################
IFS=$'\n\t'
###############################################################################
# Para reconfigurar la variable Internal Field Separator (Separador de campo interno)
# y lograr una mejor visualización y / o captura de las palabras (campos) de una
# cadena de caracteres. Habilítelo o no, según sus requerimientos y necesidades.
###############################################################################


###############################################################################
# SECCIÓN DE LA CONFIGURACIÓN PREDETERMINADA DEL TERMINAL DE EJECUCIÓN
###############################################################################
###############################################################################
setterm --reset
###############################################################################
# Para resetear la sesión y todos los parámetros de ejecución del terminal donde
# fue invocada el uso del Linux Post Install - Script Bicentenario.
# Habilítelo o no, según sus requerimientos y necesidades.
###############################################################################


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

###############################################################################
#                     REPÚBLICA BOLIVARIANA DE VENEZUELA 
#
# NOMBRE: LINUX POST INSTALL - SCRIPT BICENTENARIO (LPI-SB)
# VERSIÓN: 8.0+0
# TIPO DE PROGRAMA: SISTEMA EXPERTO
# FUNCIÓN: ASISTENTE TÉCNICO PARA S.O. GNU/LINUX BASADOS EN DEBIAN
# NOMBRE CÓDIGO: ALFA MATER (LPI-SB 8.0+0)
# PAÍS ORIGEN: REPÚBLICA BOLIVARIANA DE VENEZUELA
# CREADO POR: JOSÉ JOHAN ALBERT IZAIPE
# EMAIL: albertccs1976@hotmail.com
# NOMBRE FACEBOOK: Linux Post Install
# PAGINA PERSONAL FACEBOOK: http://www.facebook.com/linuxpostinstall
# COMUNIDAD FACEBOOK: http://www.facebook.com/pages/Script-Bicentenario/159467280799041
# TWITTER: @albertccs1976
# TELÉFONO: 0426.610.13.03
# PROMOCIONADO POR: PROYECTO TIC - TAC
# PAGINA WEB DEL PROYECTO TIC - TAC: http://www.proyectotictac.wordpress.com/
# FECHA DE LANZAMIENTO DE LA PRIMERA VERSIÓN (1.0): 07/12/2010
# FECHA DE LANZAMIENTO DE LA VERSIÓN ACTUAL (8.0+0): 01/02/2016
# FECHA DE ULTIMA ACTUALIZACIÓN: 04/02/2016
###############################################################################


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

###############################################################################
#            LINUX POST INSTALL - SCRIPT BICENTENARIO (LPI-SB)
###############################################################################
#
# Derechos de autor:
# Copyleft (C) 2016 José Johan Albert Izaipe
# 
# Licenciamiento:
#
# El Linux Post Install – Script Bicentenario no viene con ninguna garantía. El 
# Autor no se hace responsable si se al aplicarse el Sistema Operativo se
# corrompe, daña o inutiliza.
#
# El Linux Post Install – Script Bicentenario 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, ya sea la versión 3 o cualquier versión posterior, según sea de 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 Pública General de GNU 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 el, deberá siempre mencionar al autor original de la misma:   
#
# Desarrollador : José Albert
# Nick          : Linux Post Install
# Twitter       : @albertccs1976
# Facebook      : ttp://www.facebook.com/linuxpostinstall
# Telegram      : (+58) 416-6101303
# Canal Telegram: https://telegram.me/proyectotictac
#
# Este SCRIPT tiene un doble propósito:
#
# 1.- Educativo: Mostrar las buenas practicas en la diseño e implementación de
#                Script de Shell para Linux
#
# 2.- Técnico: Realizar vía terminal o gráfica las diversas acciones (módulos)
#              que se le añadan para su ejecución automatizada.            
#
###############################################################################
#            LINUX POST INSTALL - SCRIPT BICENTENARIO (LPI-SB)
###############################################################################

After inserting your Shebang and BSM, what you should then insert into your Shell script It is a module that validates that indeed only the superuser root can execute it. This and any other module, function, variable, command or action in general it can be carried out many ways, so what you will see next is a simple way, Of the many possible and probable ways in which said action can or could be carried out:


###############################################################################
# INICIO DEL MODULO DE VALIDACIÓN PERMISO DE SUPERUSUARIO (ROOT) SOBRE EL LPI-SB
###############################################################################

# ESTE MODULO VALIDA QUE SOLO EL SUPERUSUARIO (USUARIO ROOT) PUEDA EJECUTAR
# EL LINUX POST INSTALL - SCRIPT BICENTENARIO.

clear

setterm -background red

if [[ "$(id -u)" != "0" ]]; then
   echo "ESTE SCRIPT DEBE SER EJECUTADO COMO ROOT"
   sleep 3
   clear      
  else
   echo "ESTE SCRIPT SERA EJECUTADO COMO SUPERUSUARIO (ROOT)"
   sleep 3
   clear
fi

###############################################################################
# FINAL DEL MODULO DE VALIDACIÓN PERMISO DE SUPERUSUARIO (ROOT) SOBRE EL LPI-SB
###############################################################################

Later, in future posts we will see among many other things, how to create modules (sections) that perform functions such as:

  • SCRIPT ENVIRONMENT VARIABLES MODULE
  • 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, and learn to use 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.

But always 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.   Edward Cuomo said

    I invite you to see and collaborate in the BashX project (https://github.com/reduardo7/bashx), a 100% Bash Framework with which you can create applications in a very simple and clear way. I hope it will be you useful!

  2.   Jose Albert said

    I already saw it and download! Check the codes, explore its structure and try to install it but it gave me an error.

    But I think that because if I'm not mistaken it has been created for a long time and it still needs to adjust some parameters manually, but in summary the idea seems great to me. It is, if I understood correctly, how to automate the insertion of predefined modules to suit the user, within a script. It's like automating what I'm suggesting and explaining by hand!

    Right or wrong! Anyway, tell us yourself a little about it or have one entered about it!