In this particular case, I'd like to add a confirm in Bash for
Are you sure? [Y/n]
for Mercurial's hg push ssh://username@www.example.com//somepath/morepath
, which is actually an alias. Is there a standard command that can be added to the alias to achieve it?
The reason is that hg push
and hg out
can sound similar and sometimes when I want hgoutrepo
, I may accidentlly type hgpushrepo
(both are aliases).
Update: if it can be something like a built-in command with another command, such as: confirm && hg push ssh://...
that'd be great... just a command that can ask for a yes
or no
and continue with the rest if yes
.
Below code is combining two things
shopt -s nocasematch that will take care of case insensitive
and if condition that will accept both the input either you pass yes,Yes,YES,y.
shopt -s nocasematch
if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
then exit 0
fi
Confirmations are easily bypassed with carriage returns, and I find it useful to continually prompt for valid input.
Here's a function to make this easy. "invalid input" appears in red if Y|N is not received, and the user is prompted again.
You can change the default prompt by passing an argument
These are more compact and versatile forms of Hamish's answer. They handle any mixture of upper and lower case letters:
Or, for Bash >= version 3.2:
Note: If
$response
is an empty string, it will give an error. To fix, simply add quotation marks:"$response"
. – Always use double quotes in variables containing strings (e.g.: prefer to use"$@"
instead$@
).Or, Bash 4.x:
Edit:
In response to your edit, here's how you'd create and use a
confirm
command based on the first version in my answer (it would work similarly with the other two):To use this function:
or
No pressing enter required
Here's a longer, but reusable and modular approach:
0
=yes and1
=nozsh
andbash
.Defaulting to "no" when pressing enter
Note that the
N
is capitalsed. Here enter is pressed, accepting the default:Also note, that
[y/N]?
was automatically appended. The default "no" is accepted, so nothing is echoed.Re-prompt until a valid response is given:
Defaulting to "yes" when pressing enter
Note that the
Y
is capitalised:Above, I just pressed enter, so the command ran.
No default on enter - require
y
orn
Here,
1
or false was returned. Note no capitalisation in[y/n]?
Code
This isn't exactly an "asking for yes or no" but just a hack: alias the
hg push ...
not tohgpushrepo
but tohgpushrepoconfirmedpush
and by the time I can spell out the whole thing, the left brain has made a logical choice.Try,