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

printf "Pi to 9 decimal places = %1.9f" $PI # It even rounds off correctly.<br />

printf "\n"<br />

# Prints a line feed,<br />

# equivalent to 'echo'.<br />

printf "Constant = \t%d\n" $DecimalConstant # Inserts tab (\t)<br />

printf "%s %s \n" $Message1 $Message2<br />

echo<br />

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

# Simulation of C function, 'sprintf'.<br />

# Loading a variable with a formatted string.<br />

echo<br />

Pi12=$(printf "%1.12f" $PI)<br />

echo "Pi to 12 decimal places = $Pi12"<br />

Msg=`printf "%s %s \n" $Message1 $Message2`<br />

echo $Msg; echo $Msg<br />

# As it happens, the 'sprintf' function can now be accessed<br />

# as a loadable module to Bash, but this is not portable.<br />

exit 0<br />

Formatting error messages is a useful application of printf<br />

E_BADDIR=65<br />

var=nonexistent_directory<br />

error()<br />

{<br />

printf "$@" >&2<br />

# Formats positional params passed, and sents them to stderr.<br />

echo<br />

exit $E_BADDIR<br />

}<br />

cd $var || error $"Can't cd to %s." "$var"<br />

read<br />

# Thanks, S.C.<br />

"Reads" the value of a variable from stdin, that is, interactively fetches input from the keyboard.<br />

The −a option lets read get array variables (see Example 26−3).<br />

Example 11−2. Variable assignment, using read<br />

#!/bin/bash<br />

echo −n "Enter the value of variable 'var1': "<br />

# The −n option to echo suppresses newline.<br />

read var1<br />

# Note no '$' in front of var1, since it is being set.<br />

Chapter 11. Internal Commands and Builtins 126

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

Saved successfully!

Ooh no, something went wrong!