15

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!"
...
2
  • 2
    why are you using & and sleeping there? you should run it synchronously... Commented Jul 7, 2012 at 9:12
  • @cha0site I am starting some external development tool and without & the tool will start only the first command Commented Jul 7, 2012 at 15:54

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I does not work with double [[ brackets, but it works with single [ bracket.
It really should work with [[. Are you sure you're using bash, with #! /bin/bash as the first line of your script?
there is no #! /bin/bash on the first line. I guess that may be the problem as I did not explicitly said it's bash.
@sandalone the spaces between [[ and $ and ; matter in some ridiculous way, I found,..
1

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!

2 Comments

You might want to try to avoid eval if you can. One idea would be to encapsulate each command in a function which either describes itself or runs itself depending on how you invoke it.
The lowercase parameter expansion ${,,} requires Bash 4. And see BashFAQ/050.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.