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

then<br />

echo "(null)"<br />

return<br />

fi<br />

#+ send error message<br />

#+ (C−style void−pointer error message)<br />

#+ and return from function.<br />

echo "$@" | tr A−Z a−z<br />

# Translate all passed arguments ($@).<br />

return<br />

# Use command substitution to set a variable to function output.<br />

# For example:<br />

# oldvar="A seT of miXed−caSe LEtTerS"<br />

# newvar=`tolower "$oldvar"`<br />

# echo "$newvar" # a set of mixed−case letters<br />

#<br />

# Exercise: Rewrite this function to change lowercase passed argument(s)<br />

# to uppercase ... toupper() [easy].<br />

}<br />

• Use special−purpose comment headers to increase clarity and legibility in scripts.<br />

## Caution.<br />

rm −rf *.zzy<br />

## The "−rf" options to "rm" are very dangerous,<br />

##+ especially with wildcards.<br />

#+ Line continuation.<br />

# This is line 1<br />

#+ of a multi−line comment,<br />

#+ and this is the final line.<br />

#* Note.<br />

#o List item.<br />

#> Another point of view.<br />

while [ "$var1" != "end" ] #> while test "$var1" != "end"<br />

• Using the $? exit status variable, a script may test if a parameter contains only digits, so it can be<br />

treated as an integer.<br />

#!/bin/bash<br />

SUCCESS=0<br />

E_BADINPUT=65<br />

test "$1" −ne 0 −o "$1" −eq 0 2>/dev/null<br />

# An integer is either equal to 0 or not equal to 0.<br />

# 2>/dev/null suppresses error message.<br />

if [ $? −ne "$SUCCESS" ]<br />

then<br />

echo "Usage: `basename $0` integer−input"<br />

exit $E_BADINPUT<br />

fi<br />

let "sum = $1 + 25"<br />

echo "Sum = $sum"<br />

# Would give error if $1 not integer.<br />

# Any variable, not just a command line parameter, can be tested this way.<br />

exit 0<br />

Chapter 34. Miscellany 349

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

Saved successfully!

Ooh no, something went wrong!