Cody A. Ray

Elegant Shell Scripts

April 20, 2013 · updated April 18, 2013

Shell scripts aren’t known for being the cleanest, most elegant part of your technology. But I argue that, as a vital piece of your stack, they should be afforded the same thought and care as other parts of your codebase.

Sure, shell scripts like bash have some inherent limitations, but they shouldn’t prevent you from following standard software engineering principles.

For example, bash functions can’t return values, but functionality should still be broken into small reusable chunks each having a single responsibility. Just call the function in a subshell and have it echo the result. Or use a standardized return value. Plus, you can easily take advantage of the return codes of invoked programs.

Consider this simple script for generating a random alphanumeric identifier that’s unique across a group of files within a folder (e.g., xml files grouped by folder).


#!/usr/bin/env bash
# Generates a unique random fixed-length alphanumeric identifier
# Usage: ./bin/generate-id [vendor|product] [length]
#
# Example: generate a unique id
#        ./bin/generate-id
#
# Example: generate a unique eight-character product id
#        ./bin/generate-id product 8

<p>path=${1:-vendor product}<br />
length=${2:-7}</p>

<p>function generate_id {<br />
  # https://coderwall.com/p/4zux3a<br />
  echo $(cat /dev/urandom | LC_CTYPE=C tr -dc "a-zA-Z0-9" | head -c $length)<br />
}</p>

<p>function id_exists {<br />
  grep -qr $1 $2<br />
}</p>

<p>id=$(generate_id)<br />
while id_exists $id $path ; do<br />
  id=$(generate_id)<br />
done</p>

<p>echo $id<br />

Looks good to this software engineer. :)

© 2009–2026 Cody A. Ray
RSSGitHubLinkedIn