27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

return 0<br />

}<br />

It is even possible for a script to source itself, though this does not seem to have any practical<br />

applications.<br />

Example 11−19. A (useless) script that sources itself<br />

#!/bin/bash<br />

# self−source.sh: a script sourcing itself "recursively."<br />

# From "Stupid Script Tricks," Volume II.<br />

MAXPASSCNT=100<br />

# Maximum number of execution passes.<br />

echo −n "$pass_count "<br />

# At first execution pass, this just echoes two blank spaces,<br />

#+ since $pass_count still uninitialized.<br />

let "pass_count += 1"<br />

# Assumes the uninitialized variable $pass_count<br />

#+ can be incremented the first time around.<br />

# This works with Bash and pdksh, but<br />

#+ it relies on non−portable (and possibly dangerous) behavior.<br />

# Better would be to set $pass_count to 0 if non−initialized.<br />

while [ "$pass_count" −le $MAXPASSCNT ]<br />

do<br />

. $0 # Script "sources" itself, rather than calling itself.<br />

# ./$0 (which would be true recursion) doesn't work here.<br />

done<br />

# What occurs here is not actually recursion,<br />

#+ since the script effectively "expands" itself<br />

#+ (generates a new section of code)<br />

#+ with each pass throught the 'while' loop',<br />

# with each 'source' in line 20.<br />

#<br />

# Of course, the script interprets each newly 'sourced' "#!" line<br />

#+ as a comment, and not as the start of a new script.<br />

echo<br />

exit 0 # The net effect is counting from 1 to 100.<br />

# Very impressive.<br />

exit<br />

exec<br />

# Exercise:<br />

# −−−−−−−−<br />

# Write a script that uses this trick to do something useful.<br />

Unconditionally terminates a script. The exit command may optionally take an integer argument,<br />

which is returned to the shell as the exit status of the script. It is good practice to end all but the<br />

simplest scripts with an exit 0, indicating a successful run.<br />

If a script terminates with an exit lacking an argument, the exit status of the script is<br />

the exit status of the last command executed in the script, not counting the exit.<br />

Chapter 11. Internal Commands and Builtins 141

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!