3 ms·
The article mentions loops with an incrementing variable, e.g., i=$((i+1)). It is also possible to do this without loops. Is it faster. Left to the reader to de
by 3xblah 7y ago
The article mentions loops with an incrementing variable, e.g., i=$((i+1)). It is also possible to do this without loops. Is it faster. Left to the reader to decide. I used this technique sometimes so I could check on the progress of a script while it is running and also continue a script later where I left off. It also allowed me to stop the script by removing a file. At the time, the shell I used had not yet implemented LINENO, which is also very useful when scripts are terminated before finishing.
For example, if I wanted to "loop" 15 times^1
To begin, first create a file that stores the count.^2 It also acts as a way to stop the "loop" from advancing if it is removed.
echo 0 > x
Then create a file that acts as an "on/off switch" to stop the script, e.g., if it is not runnning in the foreground.
> x-on
Then run the script. The "prologue" and "epilogue" use only shell built-ins. No external programs or Bash-isms are required.^3
#! /bin/sh
CRAWL_DELAY=30;
test -f x||exit $LINENO;
test -f x-on||exit $LINENO;
read x < x;
test $x -le 14||exit $LINENO;
# do stuff;
echo https://example.com/$x;
sleep CRAWL_DELAY;
echo $((x+1)) >x;
test -f x-on||exit $LINENO;
test -f $0||exit $LINENO;
$0
To see progress,
cat x
To stop the script before it finishes,
rm x-on
To restart the script and continue where left off,
> x-on
and run the script.
1. Sometimes I did not have access to a program like seq or jot so something like this was not possible
for x in $(seq 15);do
echo https://example.com/$x;
done
2. I always work in a tmpfs-mounted directory so these "files" are just memory, they are not saved on "disk".
3. Bash has too many features for this author to keep track of, like, e.g., base conversion
echo $((16#a))