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.

Chapter 33. Scripting With Style<br />

Get into the habit of writing shell scripts in a structured and systematic manner. Even "on−the−fly" and<br />

"written on the back of an envelope" scripts will benefit if you take a few minutes to plan and organize your<br />

thoughts before sitting down and coding.<br />

Herewith are a few stylistic guidelines. This is not intended as an Official Shell Scripting Stylesheet.<br />

33.1. Unofficial Shell Scripting Stylesheet<br />

• Comment your code. This makes it easier for others to understand (and appreciate), and easier for you<br />

to maintain.<br />

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

# It made perfect sense when you wrote it last year, but now it's a complete mystery.<br />

# (From Antek Sawicki's "pw.sh" script.)<br />

Add descriptive headers to your scripts and functions.<br />

#!/bin/bash<br />

#************************************************#<br />

# xyz.sh #<br />

# written by Bozo Bozeman #<br />

# July 05, 2001 #<br />

# #<br />

# Clean up project files. #<br />

#************************************************#<br />

BADDIR=65<br />

# No such directory.<br />

projectdir=/home/bozo/projects # Directory to clean up.<br />

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

# cleanup_pfiles () #<br />

# Removes all files in designated directory. #<br />

# Parameter: $target_directory #<br />

# Returns: 0 on success, $BADDIR if something went wrong. #<br />

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

cleanup_pfiles ()<br />

{<br />

if [ ! −d "$1" ] # Test if target directory exists.<br />

then<br />

echo "$1 is not a directory."<br />

return $BADDIR<br />

fi<br />

}<br />

rm −f "$1"/*<br />

return 0 # Success.<br />

cleanup_pfiles $projectdir<br />

exit 0<br />

Be sure to put the #!/bin/bash at the beginning of the first line of the script, preceding any comment<br />

headers.<br />

• Avoid using "magic numbers", [63] that is, "hard−wired" literal constants. Use meaningful variable<br />

Chapter 33. Scripting With Style 333

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

Saved successfully!

Ooh no, something went wrong!