How can I add a yes or no prompt to a script to run another one?
Asked by
+36 exposures
I'm working on a simple backup script that creates data archives. At the end of the script, I want to add an option to either run a second script that encrypts and uploads to a cloud server or just exit. I want to avoid running the second script every time. Does anyone have suggestions on how to implement a yes or no prompt for this?
Answers
You might not even need separate scripts! Just add a simple check at the end of your first script to see if the user inputs โnoโ and exit if they do. That keeps it clean and efficient.
Reply to this answer
Here's a simple way to do it:
```bash
echo -n "Want to continue? (y/n) "
read answer
if [ "$answer" = "y" ]; then
exec ./script2.sh
fi
exit 0
```
This checks the user input and runs your second script only if they say yes.
Reply to this answer
In bash, you can use the `help read` command to find more options for the read command. It has some neat features that might help you out!
Reply to this answer
Check out this example:
```bash
read -s -n 1 -p "Continue execution? (y/n) " confirm
[[ $confirm == "y" ]] || exit 0
# continue with the second script here
```
The `-s` and `-n 1` options are great because they let you accept input without needing to hit enter after typing!
Reply to this answer
Add your answer
Answers are reviewed before publication.
+dandelion roots!: Thatโs cool! By the way, can you extend that code to include a timeout? Like if the user doesn't press anything for a few seconds, the script should just exit.