Debian Codegraph @

self-source.sh

raw symbols SCIP
1 #!/bin/bash
2 # self-source.sh: a script sourcing itself "recursively."
3 # From "Stupid Script Tricks," Volume II.
4
5 MAXPASSCNT=100 # Maximum number of execution passes.
6
7 echo -n "$pass_count "
8 # At first execution pass, this just echoes two blank spaces,
9 #+ since $pass_count still uninitialized.
10
11 let "pass_count += 1"
12 # Assumes the uninitialized variable $pass_count
13 #+ can be incremented the first time around.
14 # This works with Bash and pdksh, but
15 #+ it relies on non-portable (and possibly dangerous) behavior.
16 # Better would be to initialize $pass_count to 0 before incrementing.
17
18 while [ "$pass_count" -le $MAXPASSCNT ]
19 do
20 . $0 # Script "sources" itself, rather than calling itself.
21 # ./$0 (which would be true recursion) doesn't work here. Why?
22 done
23
24 # What occurs here is not actually recursion,
25 #+ since the script effectively "expands" itself, i.e.,
26 #+ generates a new section of code
27 #+ with each pass through the 'while' loop',
28 # with each 'source' in line 20.
29 #
30 # Of course, the script interprets each newly 'sourced' "#!" line
31 #+ as a comment, and not as the start of a new script.
32
33 echo
34
35 exit 0 # The net effect is counting from 1 to 100.
36 # Very impressive.
37
38 # Exercise:
39 # --------
40 # Write a script that uses this trick to actually do something useful.