Skip to content


Elegant Shell Scripts

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
 
path=${1:-vendor product}
length=${2:-7}
 
function generate_id {
  # https://coderwall.com/p/4zux3a
  echo $(cat /dev/urandom | LC_CTYPE=C tr -dc "a-zA-Z0-9" | head -c $length)
}
 
function id_exists {
  grep -qr $1 $2
}
 
id=$(generate_id)
while id_exists $id $path ; do
  id=$(generate_id)
done
 
echo $id

Looks good to this software engineer. :)

Posted in Tutorials.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

 



Log in here!