Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple if/else bash script which reacts to user's yes/no input? [duplicate]

Tags:

bash

shell

I basically have a bash script which executes 5 commands in a row. I want to add a logic which asks me "Do you want to execute command A" and if I say YES, the command is executed, else the script jumps to another line and I see the prompt "Do you want to execute command B".

The script is very simple and looks like this

echo "Running A"
commandA &
sleep 2s;
echo "done!"

echo "Running B"
commandB &
sleep 2s;
echo "done!"
...
like image 722
sandalone Avatar asked Jul 07 '12 09:07

sandalone


People also ask

How do you ask yes or no in bash?

In that case, we can simply wrap our yes/no prompt in a while loop. #!/bin/bash while true; do read -p "Do you want to proceed? (yes/no) " yn case $yn in yes ) echo ok, we will proceed; break;; no ) echo exiting...; exit;; * ) echo invalid response;; esac done echo doing stuff...

How do you use YES in bash?

By default, `yes` command repeats the character 'y' if no string value is specified with this command. When `yes` command uses with pipe and another command then it will send the value 'y' or `yes` for any confirmation prompt. This command can help to save time by doing many confirmation tasks automatically.


2 Answers

Use the read builtin to get input from the user.

read -p "Run command $foo? [yn]" answer
if [[ $answer = y ]] ; then
  # run the command
fi

Put the above into a function that takes the command (and possibly the prompt) as an argument if you're going to do that multiple times.

like image 81
Mat Avatar answered Sep 20 '22 06:09

Mat


You want the Bash read builtin. You can perform this in a loop using the implicit REPLY variable like so:

for cmd in "echo A" "echo B"; do
    read -p "Run command $cmd? "
    if [[ ${REPLY,,} =~ ^y ]]; then
        eval "$cmd"
        echo "Done!"
    fi
done

This will loop through all your commands, prompt the user for each one, and then execute the command only if the first letter of the user's response is a Y or y character. Hope that helps!

like image 32
Todd A. Jacobs Avatar answered Sep 20 '22 06:09

Todd A. Jacobs