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
2009-12-11 02:55:53
+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
2009-12-11 02:56:30
thanks, what do the double square brackets do?
Tom
2009-12-11 03:02:18
and can that be negated? i.e. if not match, exit?
Tom
2009-12-11 03:04:46
It has more features than `[]` including the regex match operator `=~`. See: http://mywiki.wooledge.org/BashFAQ/031
Dennis Williamson
2009-12-11 03:09:44
`if [[ ! $REPLY =~ [Yy] ]]`
Dennis Williamson
2009-12-11 03:11:04
one small issue. If user enters anything that starts with y|Y, it will go through. [[ $a =~ "^[Yy]$" ]]
2009-12-11 05:53:06
+1
A:
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
kingsindian
2009-12-11 02:57:04
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
2009-12-11 02:59:06
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
2009-12-11 02:59:43
+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
2009-12-11 05:33:59