How can I ask the user for confirmation in a bash file?

Asked

Viewed 1,698 times

10

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

  • In addition to the answers below... if bash shell, can use the TMOUT variable to set a timeout to the user and to avoid case/minuscule problems : if echo "$resp" | grep -qi "^sim$" ; then

5 answers

9

From what I understood a possible solution is this below :

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

8

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

5

The parameter -n 1 causes the command to read wait for the typing of only one character, without the need to press enter.

The command read has a default return variable called $REPLY, by specifying 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’ve helped!

4

1

Using read, as function:

#!/usr/bin/bash

true=1
false=0

confok(){
    read -p "$1 [S/n]"
    [[ ${REPLY^} == "" ]] && return $true
    [[ ${REPLY^} == N ]] && return $false || return $true
}

confno(){
    read -p "$1 [N/s]"
    [[ ${REPLY^} == "" ]] && return $false
    [[ ${REPLY^} == N  ]] && return $false || return $true
}

confno "Remover?"
LOK=$?

if (( $LOK )); then
    echo "Sim"
else
    echo "Nao"
fi

confok "Continuar?"
LOK=$?

if (( $LOK )); then
    echo "Sim"
else
    echo "Nao"
fi

Output:

Remover? [N/s] n
Nao
Continuar? [S/n] s
Sim

Browser other questions tagged

You are not signed in. Login or sign up in order to post.