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!"
...
sandalone
  • 41,141
  • 63
  • 222
  • 338

2 Answers2

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • I does not work with double [[ brackets, but it works with single [ bracket. – sandalone Jul 07 '12 at 16:04
  • 1
    It really should work with `[[`. Are you sure you're using `bash`, with `#! /bin/bash` as the first line of your script? – Mat Jul 07 '12 at 16:59
  • 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 Jul 09 '12 at 11:59
  • @sandalone the spaces between `[[` and `$` and `;` matter in some ridiculous way, I found,.. – Bastiaan Sep 13 '17 at 22:11
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!

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 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. – tripleee Jul 07 '12 at 09:53
  • The lowercase parameter expansion `${,,}` requires Bash 4. And see [BashFAQ/050](http://mywiki.wooledge.org/BashFAQ/050). – Dennis Williamson Jul 07 '12 at 10:56