Learn how to calculate the DNI letter using a Bash script

After satisfying the requirements for be able to run bash scripts, and understand how to define functions, learn how return values ​​in bash functions. To do this we are going to create a small but powerful program in Bash that calculate the letters of the DNI. I have good news: Bash can too be installed on Windows 10. With what can be added all the power of Linux in operating systems, let's say ... different.

First of all, we have to understand how the substrings, which, as in any language, has the possibility of return parts of a string from the indication of the chain, the position and the length of the segment. Let's look at an example of this behavior. We create our script with

$ touch prueba_substring
$ 

Then we add the following code with your preferred editor. In terminal mode my preferred editor is mcedit. But lately I see that nano is gaining strength.

 
#!/usr/bin/env bash 
# Demo comportamiento de substrings en Bash 
# Pedro Ruiz Hidalgo 
# version 1.0.0 
# Febrero 2017 

ret="\n" 
CADENA="siempre uso Linux con Ubuntu y Ubunlog, claro!" 
#      "0123456789012345678901234567890123456789012345" 
#      "          1         2         3         4     " 
# (usa la regla para medir los caracteres) 

echo -e $ret ${CADENA:12} 
echo -e $ret ${CADENA:12:5} 
echo -e $ret "Aprendo en ${CADENA:31:7}" 
exit 0 

Adding the permissions and executing like this:

$ chmod +x prueba_substring
$ ./prueba_substring
$

It should, if everything went well, return the following result:

 Linux Con Ubuntu y Ubunlog, claro!

 Linux

 Aprendo en Ubunlog

Substring Operation

As you can see above I have highlighted lines 13 to 15 from the script and step to explain your code. Echo with the parameter "-e" lets show the next line character, we have defined this character in the line 7 and assigned to the variable «ret».

Line 13: I show the substring (substring) of the CHAIN ​​variable, described in line 8, from position 12. Always starting to count from position 0.

Line 14: From position 12 of the CHAIN ​​variable, I show a segment of 5. As you will verify this corresponds to the substring "Linux".

Line 15: I compose a new string enclosed in quotes I start as «I learn in«, to continue with a substring of the CHAIN ​​variable from position 31, taking a segment of 7: this corresponds to «Ubunlog».

Postback functions

The return mechanism with Bash is produced by the "return" command, although, when we have to match it to a Bash variable, it implements a "strange" mechanism, which you have to get used to. Let's look at the following example:

#!/usr/bin/env bash

function suma(){
  local a=$1
  local b=$2
  return $(( $a + $b ))
}

suma 12 23
retorno=$?
echo $retorno

Functions must always be defined before using them in Bash, therefore, after the shebang we declare the function sum, on line 4 we define by means of «local» the assignment of the first of the parameters ($ 1) to the variable "a". Identical procedure on line 5, where we assign the second parameter a ($ 2) to the variable «b». In line nine we call the sum function with two parameters that will be converted by the mechanism described in the variables "a" and "b" and with "return" we return them added, as can easily be seen in the instructions for the function.

We assign the variable "return" in the line 10 the result of the execution of the function sum.

After studying and understanding the way in which returns of values ​​and assignment to variables are practiced Let's go to see our program of the calculation of DNI letters with Bash.

Script to calculate DNI letters with Bash

#!/usr/bin/env bash

nl="\n"

LETRAS="TRWAGMYFPDXBNJZSQVHLCKEO"
NORMAL=0
ERROR=66

if [ $# -lt 1 ];
then
	echo -e "$nl Cálculo DNI, introduce número$nl"
	read -r ndni
	[ -z "${ndni//[0-9]}" ] && [ -n "$ndni" ] || echo "Sólo números" && exit $ERROR
else
	ndni=$1
fi

modulo ()
{
	return $(( $ndni  % 23 ))
}

modulo ndni
mod=$?
echo $ndni-${LETRAS:$mod:1}
exit $NORMAL

La letter of our DNI It corresponds to number module 23. This is, we divide the number by 23 y instead of looking at the quotient, we observe the rest of the division. The other words, like numbers divisible by 23 will give zero, the letter that corresponds to it is the «T», since this is position 0, as we have seen in the script above, all substrings start counting from zero. That is, with the module we will always obtain numbers between 0 (letter "T") and 22 (letter "O"). In Bash, as in other languages the module is obtained by means of the percent operator «%».

At Lóleo Eventos, line 5 we define the letters in your order. It's obvious, the order cannot be changed for reliable results. In the if of the line 9 we are asking if when calling the script there was a number as a parameter. In case there is no parameter, we request it by keyboard with the instructions from lines 11 to 13. If the script was called with a number to calculate the order on line 15, it assigns this parameter to the variable «ndni».

In line 23 we refer to the modulo function through the parameter of variable «ndni», either it has been collected as a parameter in bash, or by keyboard as input. In line 24 the return of the function is assigned to the variable «mod». On the 25 m linewe show the number, a dash and the letter corresponding to the position according to the calculation of the modulus and the substring.

Testing our DNI script

$ ./dni 12345678
12345678-Z

O well,

$ ./dni

 Cálculo DNI, Introduce número

All our scripts should include a parameter "-a" for the author and another "-h" for help and syntax. As we have seen in previous articles or I leave it to you to avoid making the code more cumbersome.
I hope and hope that this article has been of your interest.


4 comments, leave yours

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.   Omar B.M. said

    Hello, can someone help me? I need to install lubuntu to my old desktop computer but it won't let me install via USB and the dvd drive is damaged, I just want to install http://www.plop.at to Ubuntu 16.04 LTS but I don't know how to do it. Thanks

    1.    Pedro Ruiz Hidalgo placeholder image said

      omar

      As you mentioned, the situation is not very promising: usb is not allowed and dvd drive is damaged. But you also comment that the "computer is old", that means you have a new one. Try putting the installation on a hard drive from your working computer and trying to install it from that drive.

      regards

    2.    Cesar Deba said

      Do you have a computer and a removable box? Mount the hard drive of the old computer in the removable usb box and start the installation disk.
      Linux and Unix do not take into account the hardware at boot level, with which you can put the disk again with linux installed.

    3.    Omar B.M. said

      Thank you very much I tell you that what I did was to go from Ubuntu 16.04 to Lubuntu 16.04 within the same operating system hehe and that is how my old computer was working well hehe greetings from Colombia.