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

Example A−15. password: Generating random 8−character passwords<br />

#!/bin/bash<br />

# May need to be invoked with #!/bin/bash2 on older machines.<br />

#<br />

# Random password generator for bash 2.x by Antek Sawicki ,<br />

# who generously gave permission to the document author to use it here.<br />

#<br />

# ==> Comments added by document author ==><br />

MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"<br />

LENGTH="8"<br />

# ==> May change 'LENGTH' for longer password, of course.<br />

while [ "${n:=1}" −le "$LENGTH" ]<br />

# ==> Recall that := is "default substitution" operator.<br />

# ==> So, if 'n' has not been initialized, set it to 1.<br />

do<br />

PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"<br />

# ==> Very clever, but tricky.<br />

# ==> Starting from the innermost nesting...<br />

# ==> ${#MATRIX} returns length of array MATRIX.<br />

# ==> $RANDOM%${#MATRIX} returns random number between 1<br />

# ==> and length of MATRIX − 1.<br />

# ==> ${MATRIX:$(($RANDOM%${#MATRIX})):1}<br />

# ==> returns expansion of MATRIX at random position, by length 1.<br />

# ==> See {var:pos:len} parameter substitution in Section 3.3.1<br />

# ==> and following examples.<br />

# ==> PASS=... simply pastes this result onto previous PASS (concatenation).<br />

# ==> To visualize this more clearly, uncomment the following line<br />

# ==> echo "$PASS"<br />

# ==> to see PASS being built up,<br />

# ==> one character at a time, each iteration of the loop.<br />

done<br />

let n+=1<br />

# ==> Increment 'n' for next pass.<br />

echo "$PASS"<br />

# ==> Or, redirect to file, as desired.<br />

exit 0<br />

+<br />

James R. Van Zandt contributed this script, which uses named pipes and, in his words, "really exercises<br />

quoting and escaping".<br />

Example A−16. fifo: Making daily backups, using named pipes<br />

#!/bin/bash<br />

# ==> Script by James R. Van Zandt, and used here with his permission.<br />

Appendix A. Contributed Scripts 388

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

Saved successfully!

Ooh no, something went wrong!