Useful shell scripts in any program

Bash It is a computer program whose function is to interpret orders. It is based on the shell of Unix and was written for the project GNU being the default shell in most distributions of GNU / Linux. His name is an acronym for Bourne–Again Shell (another shell bourne), making a play on words (born-again means rebirth) about him Bourne shell (sh), which was one of the first major interpreters of Unix.

Today we are going to show some shell scripts that can be very useful for developers. Most work in any shell Unix, although some require that they be specifically executed by Bash.

Prevent non-privileged users from running the script

Some scripts perform administrative tasks so we might want only the root user to run the script. In that case we can use something like this:

#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "Este script debe ser ejecutado por el usuario root" 1>&2
exit 1
fi

Allow script execution only to a specific user

Similar to the code above, we might want only a specific user to run the script. We do it so:

#!/bin/bash
AUTHORIZED_USER="usuario_permitido"
if [ $USER != $AUTHORIZED_USER ]; then
echo "Este script debe ser ejecutado por el usuario $AUTHORIZED_USER" 1>&2
exit 1
fi

Verify that a service / process is running

If we want to know if there are processes of any service or program running we could use this script (in this case it verifies that the demon of Apache is running):

#!/bin/sh
SERVICE='httpd'
if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
echo "El servicio $SERVICE esta ejecutandose"
else
echo "Chanfle! El servicio $SERVICE esta detenido"
fi

Create a lock file

Sometimes we must make sure that the script does not run two or more times simultaneously. For this we can make use of the lock files. This is a simple version of a script that allows us to do this:

#!/bin/bash
lockfile=/var/lock/loquesea.lock
if [ ! -e $lockfile ]; then
touch $lockfile
echo "hago muchas cosas importantes aqui"
rm $lockfile
else
echo "ya hay otro proceso corriendo"
fi

In this case, it is verified that the file whatever.lock exist. In case it exists, the script DOES NOT execute its tasks. If it doesn't exist, it creates the file, runs the tasks it needs to run, and removes it. But, this is not entirely reliable. What would happen if while our script is running it is closed abruptly?

In that case the lock file would not be deleted, and therefore it would not allow us to run the script again. To cover those cases, we could make use of the trap command that allows us to execute commands in case our script ends unexpectedly. This is a more advanced version that also saves the PID of the script that executes it within the lock file:

#!/bin/bash
lockfile=/var/lock/loquesea.lock
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
echo "hago muchas cosas aqui tranquilamente"
rm -f "$lockfile"
trap - INT TERM EXIT
else
echo "Ya hay otro proceso de este script ejecutandose"
echo "corriendo con el PID: $(cat $lockfile)"
fi

Let's understand the command a little better systematic trap: every time. Its syntax is basically this: trap command signal [signal…]; where signal is the termination signal you want to catch. If you want to see a list of available signals you can run the command kill -l. For the previous case, the INT signals were used (captures the termination produced by a Ctrl + c), TERMS (termination produced by kill command) and EXIT (normal termination of a script, either because there are no more lines to run or because it comes across the exit command).

Options menu

To make a menu where we allow the user to select a series of options we can use the following scheme:

#!/bin/bash
clear
while :
do
echo " Escoja una opcion "
echo "1. quien soy?"
echo "2. cuanto espacio tengo"
echo "3. que es esto?"
echo "4. Salir"
echo -n "Seleccione una opcion [1 - 4]"
read opcion
case $opcion in
1) echo "este eres:";
whoami;;
2) echo "tienes esto";
df;;
3) uname -r;;
4) echo "chao";
exit 1;;
*) echo "$opc es una opcion invalida. Es tan dificil?";
echo "Presiona una tecla para continuar...";
read foo;;
esac
done

Ask for confirmation before running a script

Sometimes it is useful to have the user confirm the execution of a batch of statements, that is, the typical message that asks the user to type yes or no. We can do this like this:

#!/bin/bash
while true; do
echo
read -p "esta seguro de hacer lo que sea que vaya a hacer " yn
case $yn in
yes ) break;;
no ) exit;;
* ) echo "por favor responda yes o no";;
esac
done
echo "si se ejecuta esto es que aceptaste"

End of article. Simply great 😀

Editorial: You have to be careful with spaces and tabs, which for some reason are not coming out ¬¬


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.   KZKG ^ Gaara said

    Damn they are great O_O ... it will help a lot to my little things that I do in Bash 😀

  2.   ren434 said

    The scripts are super! What a great contribution seriously, just what I was looking for.

    PS: The forum is down.

    1.    KZKG ^ Gaara said

      Yes, the server where the forum is mounted is offline, no idea why ... we wrote an email to the friend who takes care of it, to see what he responds to us 🙂

      Greetings.

  3.   ren434 said

    Ah well, let's hope it's nothing serious.

  4.   left handed said

    Was that "chaff" also included in Code Ninja? XD

  5.   taregon said

    I like the power of bash 😉 and they told me what the C language was for…, because in shell script there are many familiar commands.

  6.   Christopher said

    Thank you, I really liked

  7.   angel blade said

    Validation of input parameters is very useful. I didn't know how to make the menus =)

  8.   Hyuuga_Neji said

    Great…. now I can give some "hardness" to my script churros hehehe

  9.   ravens said

    A great pleasure to see how our humble work at CodeNinja serves the international linux community

    1.    KZKG ^ Gaara said

      Clear! 🙂
      Everything is to help and contribute together, and not to create flames, right? 😉

  10.   diego said

    The process script that is running could be improved a little by putting the option to choose the process you want to know about, it would look something like this:

    #! / Bin / bash
    echo "Choose a service"
    read SERVICE
    # SERVICE = 'mysql'
    if ps ax | grep -v grep | grep $ SERVICE> / dev / null
    then
    echo "$ SERVICE service is running"
    else
    echo "$ SERVICE service is stopped"

  11.   Juan Carlos C said

    I have very practical scripts, but I am looking for a special script to solve a problem that I have, which is the following: We have an application server in the Company that internal users access it by telnet, and execute a special application that is limited For licenses, users abuse and open more than one telnet to take over 2 or more licenses, so the script I have thought is that by some method check which telnet process is inactive for more than 2 hours and therefore send a kill to that pid, could you help me?

    1.    diego said

      Install the following program

      aptitude install autolog

      And you have the configuration file in /etc/autolog.conf

  12.   Tito said

    Great, friend, I can ask you a question, I need a shell script with options and I have based it on yours and it works great, but one of the options has to send emails (using postifix), it asks for subject, text and recipients on the screen and what send and check that it is sent correctly, with the mailq I can see the queue and see if it was sent, but how do I send the emails by command using the variables that received subject, text and recipients? 🙁

    1.    KZKG ^ Gaara said

      Write to my email (kzkggaara[at]desdelinux[dot]net) to speak more calmly, I will be happy to help you :)

      1.    Tito said

        Great thanks friend, you passed!

  13.   Iron said

    Hello good.
    I have come across these excellent examples just when I needed a menu.
    I've started it and can't get it to work (in the previous steps).
    I have 247 elements, which refer to the different territorial domains.
    What I need is a menu from where to choose the country:
    #! / Bin / bash
    clear
    while:
    do
    echo »Choose the country to try»
    echo «1. Afghanistan (AF) »
    echo «2. Albania (AL) »
    echo «3. Germany (DE) »
    echo «5. Angola (AO) »
    echo «6. Anguilla (AI) »
    .. and continues until 247

    echo -n "Select an option [1 - 247]"
    read option
    case $ option in
    1) echo "this you are:"; whoami ;;
    2) echo "you have this"; df ;;
    3) echo ""; uname -r ;;
    4) echo "bye"; exit 1 ;;
    5) echo "this you are:"; whoami ;;
    6) echo "this you are:"; whoami ;;
    … And continues until 247
    *) echo "$ opc is an invalid option. It is so difficult?";
    echo "Press a key to continue ...";
    read foo ;;
    esac
    done

    The behavior is as follows:
    Any option except 4, which is the output, deletes the entered number and waits for a new number.
    Entering 4 comes out.
    If I put the code of 4 in any other line (let's say 150) it comes out equally without problems.
    I have also tried to put the code in this format:
    151) echo "this you are:";
    whoami ;;
    with the same result.
    I wonder if there are better options for such a long menu and of course I'm also doing wrong.
    A help would be very appreciated, thank you

  14.   Only Raul said

    excellent ... I think it's very good to get into the shell

    Thank you

  15.   frameworks said

    great hey how can i make my bash work with a file
    example:

    upload.sh fotodelavecina.jpg

    thinking that my bash script "upload.sh" has the access information to my ftp

    greetings and thanks 😀

  16.   netzulo ntx said

    Good man, thank you very much for all the scripts, I have set up a CentOS server and you don't know how well these templates come to me, please, contact me by email. I want to propose something to you

  17.   gabriel balderramos said

    Why do you use read foo when making a menu? quick answers I need