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

TESTCHARS=2<br />

SHABANG='#!'<br />

# Test first 2 characters.<br />

# Scripts begin with a "sha−bang."<br />

for file in * # Traverse all the files in current directory.<br />

do<br />

if [[ `head −c$TESTCHARS "$file"` = "$SHABANG" ]]<br />

# head −c2 #!<br />

# The '−c' option to "head" outputs a specified<br />

#+ number of characters, rather than lines (the default).<br />

then<br />

echo "File \"$file\" is a script."<br />

else<br />

echo "File \"$file\" is *not* a script."<br />

fi<br />

done<br />

exit 0<br />

Example 12−10. Generating 10−digit random numbers<br />

#!/bin/bash<br />

# rnd.sh: Outputs a 10−digit random number<br />

# Script by Stephane Chazelas.<br />

head −c4 /dev/urandom | od −N4 −tu4 | sed −ne '1s/.* //p'<br />

# =================================================================== #<br />

# Analysis<br />

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

# head:<br />

# −c4 option takes first 4 bytes.<br />

# od:<br />

# −N4 option limits output to 4 bytes.<br />

# −tu4 option selects unsigned decimal format for output.<br />

# sed:<br />

# −n option, in combination with "p" flag to the "s" command,<br />

# outputs only matched lines.<br />

# The author of this script explains the action of 'sed', as follows.<br />

# head −c4 /dev/urandom | od −N4 −tu4 | sed −ne '1s/.* //p'<br />

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

# Assume output up to "sed" −−−−−−−−> |<br />

# is 0000000 1198195154\n<br />

# sed begins reading characters: 0000000 1198195154\n.<br />

# Here it finds a newline character,<br />

# so it is ready to process the first line (0000000 1198195154).<br />

# It looks at its s. The first and only one is<br />

Chapter 12. External Filters, Programs and Commands 164

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

Saved successfully!

Ooh no, something went wrong!