I have a data-entry script which adds records to a plain-text data table. It's a fairly complicated script with a GUI dialog, and until recently it added one record at a time. To add another record, I had to launch the script again. Was there a simple way (I asked myself) to re-run the script, or exit it, from within the script?
After a lot of rummaging on the Web, I found a suitable method in William Shotts' excellent book The Linux Command Line. This article explains the details.
The method I use is based on a while loop, as shown below. The condition for while is true, meaning the loop will always run, right down to the done at the end. However, there's an if-else statement embedded in the loop. If the 'Do it again?' answer is 'yes' (y), the continue command will re-start the loop from the top. If the answer is 'no' (n), the break command kills the loop.
Here's a simple, terminal-based script called 'demo' that shows off the method:
#!/bin/bash while true; do echo "" read -p "Enter something: " var1 echo "You entered $var1" echo "" read -p "Enter something again? (y/n) " var2 if [[ $var2 == y ]]; then continue else [[ $var2 == n ]] break fi done echo "OK, exiting"
and here's the 'demo' script at work in a terminal:
Embedding the loop
My data-entry script has commands fore and aft of the commands to be repeated, so it's structured as shown below. The GUI-dialog bits are in the repeating loop. I could also put the Do another entry? question in a GUI dialog, but I'm a keyboard-y sort of person, and the script works just fine as it is!