tags:

views:

752

answers:

8

I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?

A: 

qnd: use

read VARNAME
echo $VARNAME

for a one line response without readline support. Then test $VARNAME however you want.

zen
+1  A: 

Please see How do I prompt for input in a Linux shell script?

ennuikiller
+3  A: 
read -p "Are you sure? " -n 1
if [[ $REPLY =~ ^[Yy]$ ]]
then
    # do dangerous stuff
fi

Edit:

I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.

Also, the negated form might look like this:

read -p "Are you sure? " -n 1
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    exit 1
fi
Dennis Williamson
thanks, what do the double square brackets do?
Tom
and can that be negated? i.e. if not match, exit?
Tom
It has more features than `[]` including the regex match operator `=~`. See: http://mywiki.wooledge.org/BashFAQ/031
Dennis Williamson
`if [[ ! $REPLY =~ [Yy] ]]`
Dennis Williamson
one small issue. If user enters anything that starts with y|Y, it will go through. [[ $a =~ "^[Yy]$" ]]
+1  A: 
echo are you sure?
read x
if [ "$x" = "yes" ]
then
  # do the dangerous stuff
fi
kingsindian
+1  A: 

Try the read shell builtin:

read -p "Continue (y/n)?" CONT
if [ "$CONT" == "y" ]; then
  echo "yaaa";
else
  echo "booo";
fi
A: 
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
 # do something
fi

I s a short script to read in bash and echo back results.

Philip Schlump
A: 

This what I found elsewhere, is there a better possible version?

read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
   exit
fi
Tom
+3  A: 

use case/esac.

read -p "Continue (y/n)?" choice
case "$choice" in 
  y|Y ) echo "yes";;
  n|N ) echo "no";;
  * ) echo "invalid";;
esac

advantage:

1) neater,
2) can use "OR" condition easier
3) can use character range, eg [yY][Es][Ss]
Good solution. Personally, if the bash script could really be crippling I like to have the person type out 'yes'.
SiegeX