User interaction bash scripts

    Любой приказ, который может быть неправильно понят, понимается неправильно (Армейская аксиома)

    A rare script is deprived of the need to communicate with the user. We expect that the program (utility) will do what we want from it. Therefore, tools are needed to influence them, and the program itself must explain how its work is progressing.
    With this topic, I want to consider several ways of interacting bash scripts with a user. The article is intended for beginners in scripting, but I hope experienced people will also find something interesting for themselves.

    The topic is also equipped with primitive examples that do not carry a semantic load, but allow you to see some interesting things in work.

    Variables


    The most common way to store initial data is through variables. At the very beginning of the program, several such variables are declared in which the user writes some initial data.
    #!/bin/bash
    # Вписать сюда адрес электронной почты
    EMAIL=example@gmail.com
    echo "Адрес электронной почты: $EMAIL"
    

    This method is good if there is not much data and the script is designed to be automatically executed without user intervention. It is necessary to clearly inform the user about what and where he needs to enter. It is advisable to collect all this in one place - the configuration file . You can connect it with the source command . For example, if the configuration file is in the same directory as the script, we get:
    #!/bin/bash
    source ./config.cfg
    echo "Адрес электронной почты: $EMAIL"
    

    In the config.cfg file, do not forget to put the lineEMAIL=example@gmail.com

    Command line options


    Another way to report data to the program is to specify it at the command line at startup. These parameters are contained in variables with numbers. For example: $ 0 - the name of the script, $ 1 - the first parameter, $ 2 - the second parameter, etc. There are also two auxiliary variables: $ # contains the number of arguments passed; $ @ contains all arguments passed to the script, separated by spaces.

    #!/bin/bash
    # Цикл выдаст все переданные аргументы
    for n in $@
    do
      echo "$n"
    done
    



    Questions and Confirmations



    I think many people are familiar with the question from the screenshot above. Such a dialogue can be used ... well, you yourself guessed where it can be used.
    #!/bin/bash
    echo -n "Продолжить? (y/n) "
    read item
    case "$item" in
        y|Y) echo "Ввели «y», продолжаем..."
            ;;
        n|N) echo "Ввели «n», завершаем..."
            exit 0
            ;;
        *) echo "Ничего не ввели. Выполняем действие по умолчанию..."
            ;;
    esac
    

    Please note that in the screenshot the letter “D” is large. This means the default action, that is, if the user does not enter anything, then this will be equivalent to entering "D".

    OK / FAIL


    Another way the program communicates with the user is the execution status. Most likely they are familiar to you.

    The implementation is also quite simple.
    #!/bin/bash
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_NORMAL="echo -en \\033[0;39m"
    echo -e "Удаляется файл..."
    # Команда, которую нужно отследить
    rm test_file
    if [ $? -eq 0 ]; then
        $SETCOLOR_SUCCESS
        echo -n "$(tput hpa $(tput cols))$(tput cub 6)[OK]"
        $SETCOLOR_NORMAL
        echo
    else
        $SETCOLOR_FAILURE
        echo -n "$(tput hpa $(tput cols))$(tput cub 6)[fail]"
        $SETCOLOR_NORMAL
        echo
    fi
    

    This is how the script works:

    Good people wrote an extended version of the script with logging and progress. I will gladly share the link .

    Based on the above link, the code can be simplified.
    #!/bin/bash
    red=$(tput setf 4)
    green=$(tput setf 2)
    reset=$(tput sgr0)
    toend=$(tput hpa $(tput cols))$(tput cub 6)
    echo -e "Удаляется файл..."
    # Команда, которую нужно отследить
    rm test_file
    if [ $? -eq 0 ]; then
        echo -n "${green}${toend}[OK]"
    else
        echo -n "${red}${toend}[fail]"
    fi
    echo -n "${reset}"
    echo
    


    Pseudographics


    For fans of graphical representations, there is a convenient tool: dialog . By default, it is not in the system, so let's fix it.
    sudo apt-get install dialog
    

    You can try it with a simple command:
    dialog --title " Уведомление " --msgbox "\n Свершилось что-то страшное!" 6 50
    

    Here is an example of a progress dialog:
    #!/bin/sh
    (
    c=10
    while [ $c -ne 110 ]
        do
            echo $c
            ((c+=10))
            sleep 1
    done
    ) |
    dialog --title " Тест диалога прогресса " --gauge "Please wait ...." 10 60 0
    clear
    

    Do not forget to insert clear to clear the screen so as not to leave a blue background. This utility supports many more types of dialog boxes. The main disadvantage is that by default it is not in the system.

    An alternative to dialog is whiptail , which is even present on some systems by default.

    For more information, see the links:
    http://unstableme.blogspot.com/2009/12/linux-dialog-utility-short-tutorial.html
    http://www.cc-c.de/german/linux/linux-dialog .php

    GUI


    Although there are ardent opponents of the GUI , it clearly has a right to exist. Such dialogs can be obtained using the kdialog command (if KDE is the graphical shell), or gdialog and zenity (for Gnome).

    For example, a password entry form:
    kdialog --password "Пожалуйста, введите свой пароль:"
    

    or
    gdialog --password "Пожалуйста, введите свой пароль:"
    

    Another example is one for KDE:
    kdialog --question "Вы хотите продолжить?"
    rc=$?
    if [ "${rc}" == "0" ]; then
        echo "Нажали yes"
    else
        echo "Нажали no"
    fi
    

    And for Gnome:
    #!/bin/bash
    name=$(gdialog --title "Ввод данных" --inputbox "Введите ваше имя:" 50 60 2>&1)
    echo "Ваше имя: $name"
    

    As you can see, a clear drawback of this method is its attachment to a specific desktop environment. And indeed to a graphical environment, which may be absent. But, nevertheless, it may come in handy someday.

    More details on the links:
    http://pwet.fr/man/linux/commandes/kdialog
    http://linux.about.com/library/cmd/blcmdl1_gdialog.htm
    http://www.techrepublic.com/blog/opensource/ gui-scripting-in-bash / 1667

    P.S. To be continued ...

    UPD: Added a simplified code to the "OK / FAIL" section.
    UPD2: Added an example of connecting a configuration file to the Variables section.

    The second part is published .

    Also popular now: