How can I add a yes or no prompt to a script to run another one?

April 20, 2025 4 answers
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

hatchling.count
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
turret lathe
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
sine2square
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
AxleGrease
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!

+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.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions