How can I request a user confirmation in a bash file?

9

I need to display a message on the Console and ask for a confirmation. For example, ask the user to type SIM to continue, and check this.

    
asked by anonymous 09.03.2014 / 21:43

4 answers

8

So I understand a possible solution is this:

echo "Tem certeza que blá, blá, blá ? Digite SIM para continuar ou qualquer outra coisa para terminar"
read resp
if [ $resp. != 'SIM.' ]; then
    exit 0
fi
    
09.03.2014 / 21:47
7

To request a confirmation you could also use the following:

echo "Confirmacão... (sim/não)"
read CONFIRMA

case $CONFIRMA in 
    "sim")
        # ...
        # ...
    ;;

    "não")
        # ...
        # ...           
    ;;

    *)
        echo  "Opção inválida."
    ;;
esac
    
10.03.2014 / 03:32
4

The -n 1 parameter causes the read command to wait for just one character to be entered, without pressing enter.

The command read has a default return variable called $REPLY , by assigning the declaration of a variable.

#!/bin/bash

read -p "Continuar (S/N)? " -n 1 -r

echo

case "$REPLY" in 
  s|S ) echo "Sim" ;;
  n|N ) echo "Nao" ;;
    * ) echo "Invalido" ;;
esac

exit 0

I hope I have helped!

    
09.05.2016 / 08:04
3

An interesting alternative for such cases is to use the command select

Something like this:

select i in SIM NAO
do
    case "$i" in 
        "SIM") 
            echo "continuar"; 
            ;; 
        "NAO")
            echo "parar"
            exit 0
            ;;
        *)
            echo "opção inválida"
            exit 0
            ;;
     esac
done

See more here: link

    
29.12.2014 / 01:43