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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

for i; do<br />

# "i" gets set to "@", previous values of $n.<br />

# echo "−n=$n i=$i−"<br />

(( i * i > n )) && break # Optimization.<br />

(( n % i )) && continue # Sift out non−primes using modulo operator.<br />

Primes $n $@<br />

# Recursion inside loop.<br />

return<br />

done<br />

}<br />

Primes $n $@ $n<br />

# Recursion outside loop.<br />

# Successively accumulate positional parameters.<br />

# "$@" is the accumulating list of primes.<br />

Primes 1<br />

exit 0<br />

# Uncomment lines 17 and 25 to help figure out what is going on.<br />

# Compare the speed of this algorithm for generating primes<br />

# with the Sieve of Eratosthenes (ex68.sh).<br />

# Exercise: Rewrite this script without recursion, for faster execution.<br />

+<br />

Jordi Sanfeliu gave permission to use his elegant tree script.<br />

Example A−18. tree: Displaying a directory tree<br />

#!/bin/sh<br />

# @(#) tree 1.1 30/11/95 by Jordi Sanfeliu<br />

# email: mikaku@fiwix.org<br />

#<br />

# Initial version: 1.0 30/11/95<br />

# Next version : 1.1 24/02/97 Now, with symbolic links<br />

# Patch by : Ian Kjos, to support unsearchable dirs<br />

# email: beth13@mail.utexas.edu<br />

#<br />

# Tree is a tool for view the directory tree (obvious :−) )<br />

#<br />

# ==> 'Tree' script used here with the permission of its author, Jordi Sanfeliu.<br />

# ==> Comments added by the author of this document.<br />

# ==> Argument quoting added.<br />

search () {<br />

for dir in `echo *`<br />

# ==> `echo *` lists all the files in current working directory, without line breaks.<br />

# ==> Similar effect to for dir in *<br />

# ==> but "dir in `echo *`" will not handle filenames with blanks.<br />

do<br />

if [ −d "$dir" ] ; then # ==> If it is a directory (−d)...<br />

zz=0 # ==> Temp variable, keeping track of directory level.<br />

while [ $zz != $deep ] # Keep track of inner nested loop.<br />

do<br />

echo −n "| " # ==> Display vertical connector symbol,<br />

# ==> with 2 spaces & no line feed in order to indent.<br />

Appendix A. Contributed Scripts 390

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

Saved successfully!

Ooh no, something went wrong!