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

# Uses 'awk' to strip off the filename.<br />

The mcookie command gives yet another way to generate a "unique" filename.<br />

Example 12−43. Filename generator<br />

#!/bin/bash<br />

# tempfile−name.sh: temp filename generator<br />

BASE_STR=`mcookie`<br />

POS=11<br />

LEN=5<br />

prefix=temp<br />

# 32−character magic cookie.<br />

# Arbitrary position in magic cookie string.<br />

# Get $LEN consecutive characters.<br />

# This is, after all, a "temp" file.<br />

# For more "uniqueness," generate the filename prefix<br />

#+ using the same method as the suffix, below.<br />

suffix=${BASE_STR:POS:LEN}<br />

# Extract a 5−character string, starting at position 11.<br />

temp_filename=$prefix.$suffix<br />

# Construct the filename.<br />

echo "Temp filename = "$temp_filename""<br />

# sh tempfile−name.sh<br />

# Temp filename = temp.e19ea<br />

units<br />

exit 0<br />

This utility converts between different units of measure. While normally invoked in interactive mode,<br />

units may find use in a script.<br />

Example 12−44. Converting meters to miles<br />

#!/bin/bash<br />

# unit−conversion.sh<br />

convert_units () # Takes as arguments the units to convert.<br />

{<br />

cf=$(units "$1" "$2" | sed −−silent −e '1p' | awk '{print $2}')<br />

# Strip off everything except the actual conversion factor.<br />

echo "$cf"<br />

}<br />

Unit1=miles<br />

Unit2=meters<br />

cfactor=`convert_units $Unit1 $Unit2`<br />

quantity=3.73<br />

result=$(echo $quantity*$cfactor | bc)<br />

echo "There are $result $Unit2 in $quantity $Unit1."<br />

# What happens if you pass incompatible units,<br />

#+ such as "acres" and "miles" to the function?<br />

Chapter 12. External Filters, Programs and Commands 212

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

Saved successfully!

Ooh no, something went wrong!