how.wtf

Confirmation prompt yes/no in Bash

· Thomas Taylor

Asking for user confirmation in a bash script is easy!

Yes/No prompt with default no

If the default is No for an invalid character or space, simply check if the prompt answer is y. Using read, user input can be limited to a single character using the -n 1 parameter.

1read -r -p "Are you sure? [y/N]" -n 1
2echo # (optional) move to a new line
3if [[ "$REPLY" =~ ^[Yy]$ ]]; then
4    echo "Operation continues"
5fi

Similarly, a case statement may be used:

1read -r -p "Are you sure? [y/N]" -n 1
2echo # (optional) move to a new line
3case "$REPLY" in 
4  y|Y ) echo "Operation continues";;
5  * ) echo "Operation is cancelled";;
6esac

#Bash  

Reply to this post by email ↪