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!"
...
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...
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With