Demo entry 6734694



Submitted by anonymous on Apr 21, 2018 at 13:38
Language: Bash. Code size: 10.1 kB.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0046) -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>Unofficial Shell Scripting Stylesheet</title><meta name="GENERATOR" content="Modular DocBook HTML Stylesheet Version 1.7"><link rel="HOME" title="Advanced Bash-Scripting Guide" href=""><link rel="UP" title="Scripting With Style" href=""><link rel="PREVIOUS" title="Scripting With Style" href=""><link rel="NEXT" title="Miscellany" href=""></head><body class="SECT1" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="NAVHEADER"><table summary="Header navigation table" width="100%" border="0" cellpadding="0" cellspacing="0"><tbody><tr><th colspan="3" align="center">Advanced Bash-Scripting Guide: </th></tr><tr><td width="10%" align="left" valign="bottom"><a href="" accesskey="P">Prev</a></td><td width="80%" align="center" valign="bottom">Chapter 35. Scripting With Style</td><td width="10%" align="right" valign="bottom"><a href="" accesskey="N">Next</a></td></tr></tbody></table><hr align="LEFT" width="100%"></div><div class="SECT1"><h1 class="SECT1"><a name="UNOFFICIALST"></a>35.1. Unofficial Shell Scripting Stylesheet</h1><p></p><ul><li><p>Comment your code. This makes it easier for others to
	    understand (and appreciate), and easier for you to maintain.
	    <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
#  It made perfect sense when you wrote it last year,
#+ but now it's a complete mystery.
#  (From Antek Sawicki's "" script.)</pre></font></td></tr></tbody></table>
	  </p><p>Add descriptive headers to your scripts and functions.
	    <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">#!/bin/bash

#                                #
#           written by Bozo Bozeman              #
#                July 05, 2001                   #
#                                                #
#           Clean up project files.              #

E_BADDIR=85                       # No such directory.
projectdir=/home/bozo/projects    # Directory to clean up.

# --------------------------------------------------------- #
# cleanup_pfiles ()                                         #
# Removes all files in designated directory.                #
# Parameter: $target_directory                              #
# Returns: 0 on success, $E_BADDIR if something went wrong. #
# --------------------------------------------------------- #
cleanup_pfiles ()
  if [ ! -d "$1" ]  # Test if target directory exists.
    echo "$1 is not a directory."
    return $E_BADDIR

  rm -f "$1"/*
  return 0   # Success.

cleanup_pfiles $projectdir

exit $?</pre></font></td></tr></tbody></table></p></li><li><p>Avoid using <span class="QUOTE">"magic numbers,"</span>

	     <a name="AEN20041" href=""><span class="footnote">[1]</span></a>

	    that is, <span class="QUOTE">"hard-wired"</span> literal constants. Use
	    meaningful variable names instead. This makes the script
	    easier to understand and permits making changes and updates
	    without breaking the application.

	    <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">if [ -f /var/log/messages ]
#  A year later, you decide to change the script to check /var/log/syslog.
#  It is now necessary to manually change the script, instance by instance,
#+ and hope nothing breaks.

# A better way:
LOGFILE=/var/log/messages  # Only line that needs to be changed.
if [ -f "$LOGFILE" ]
          </p></li><li><p>Choose descriptive names for variables and functions.
	    <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">fl=`ls -al $dirname`                 # Cryptic.
file_listing=`ls -al $dirname`       # Better.

MAXVAL=10   # All caps used for a script constant.
while [ "$index" -le "$MAXVAL" ]

E_NOTFOUND=95                        #  Uppercase for an errorcode,
                                     #+ and name prefixed with E_.
if [ ! -e "$filename" ]
  echo "File $filename not found."
  exit $E_NOTFOUND

MAIL_DIRECTORY=/var/spool/mail/bozo  #  Uppercase for an environmental
export MAIL_DIRECTORY                #+ variable.

GetAnswer ()                         #  Mixed case works well for a
{                                    #+ function name, especially
  prompt=$1                          #+ when it improves legibility.
  echo -n $prompt
  read answer
  return $answer

GetAnswer "What is your favorite number? "
echo $favorite_number

_uservariable=23                     # Permissible, but not recommended.
# It's better for user-defined variables not to start with an underscore.
# Leave that for system variables.</pre></font></td></tr></tbody></table>
          </p></li><li><p>Use <a href="">exit codes</a>
	    in a systematic and meaningful way.

	    <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">E_WRONG_ARGS=95
exit $E_WRONG_ARGS</pre></font></td></tr></tbody></table>
            See also <a href="">Appendix E</a>.</p><p><em>Ender</em> suggests using the <a href="">exit codes
	    in <tt class="FILENAME">/usr/include/sysexits.h</tt></a> in shell
	    scripts, though these are primarily intended for C and C++
	    programming.</p></li><li><p>Use standardized parameter flags for script invocation.
	     <em>Ender</em> proposes the following set
	     of flags.</p><p>             <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">-a      All: Return all information (including hidden file info).
-b      Brief: Short version, usually for other scripts.
-c      Copy, concatenate, etc.
-d      Daily: Use information from the whole day, and not merely
        information for a specific instance/user.
-e      Extended/Elaborate: (often does not include hidden file info).
-h      Help: Verbose usage w/descs, aux info, discussion, help.
        See also -V.
-l      Log output of script.
-m      Manual: Launch man-page for base command.
-n      Numbers: Numerical data only.
-r      Recursive: All files in a directory (and/or all sub-dirs).
-s      Setup &amp; File Maintenance: Config files for this script.
-u      Usage: List of invocation flags for the script.
-v      Verbose: Human readable output, more or less formatted.
-V      Version / License / Copy(right|left) / Contribs (email too).</pre></font></td></tr></tbody></table>
           </p><p>See also <a href="">Section G.1</a>.</p></li><li><p>Break complex scripts into simpler modules. Use functions
	    where appropriate. See <a href="">Example 37-4</a>.</p></li><li><p>Don't use a complex construct where a simpler one will do.

	    <table border="0" bgcolor="#E0E0E0" width="90%"><tbody><tr><td><font color="#000000"><pre class="PROGRAMLISTING">COMMAND
if [ $? -eq 0 ]
# Redundant and non-intuitive.

# More concise (if perhaps not quite as legible).</pre></font></td></tr></tbody></table>
          </p></li></ul><table border="0" width="100%" cellspacing="0" cellpadding="0" class="EPIGRAPH"><tbody><tr><td width="45%">&nbsp;</td><td width="45%" align="LEFT" valign="TOP"><i><p><i>... reading the UNIX source code to the Bourne shell (/bin/sh). I
        was shocked at how much simple algorithms could be made cryptic, and
	therefore useless, by a poor choice of code style. I asked myself,
	<span class="QUOTE">"Could someone be proud of this code?"</span></i></p><p><i>--Landon Noll</i></p></i></td></tr></tbody></table></div><h3 class="FOOTNOTES">Notes</h3><table border="0" class="FOOTNOTES" width="100%"><tbody><tr><td align="LEFT" valign="TOP" width="5%"><a name="FTN.AEN20041" href=""><span class="footnote">[1]</span></a></td><td align="LEFT" valign="TOP" width="95%"><p>In this context, <span class="QUOTE">"magic
	       numbers"</span> have an entirely different meaning than
	       the <a href="">magic numbers</a> used
	       to designate file types.</p></td></tr></tbody></table><div class="NAVFOOTER"><hr align="LEFT" width="100%"><table summary="Footer navigation table" width="100%" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td width="33%" align="left" valign="top"><a href="" accesskey="P">Prev</a></td><td width="34%" align="center" valign="top"><a href="" accesskey="H">Home</a></td><td width="33%" align="right" valign="top"><a href="" accesskey="N">Next</a></td></tr><tr><td width="33%" align="left" valign="top">Scripting With Style</td><td width="34%" align="center" valign="top"><a href="" accesskey="U">Up</a></td><td width="33%" align="right" valign="top">Miscellany</td></tr></tbody></table></div></body></html>

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).