Skip to content

POSIX and shell scripting

Sergey Lukin edited this page Mar 7, 2016 · 1 revision

Shell scripting is very accessible and comes in handy in so many ways but the syntax is crazy and the fact that UNIX world has many shell interpreters makes it hard to be confident about your script's cross platformness. So, this documents contains cross-platform POSIX-compliant shell scripting snippets that I found to be commonly used and hard to remember.

Shebang

#!/usr/bin/env sh

Environment

Detect OS and exit if OS is not supported (Linux and OS X are supported in this example):

OS="`uname`"
case $OS in
  'Linux')
    OS='Linux'
    ;;
  'Darwin')
    OS='Mac'
    ;;
  *)
    echo "Only Linux and OS X are supported"
    exit 1
    ;;
esac

Arguments

Probably the most exciting part of shell script is to accept input arguments, that's so powerful, isn't it. Here is what I use across my scripts:

# process command line switches
while [ $# -gt 0 ]
do
  case "$1" in
    -v)  verbose=true;;
    --out=*) OUTDIR=`echo $1 | sed -e 's/^[^=]*=//g'`;;
    --no-cache) cache=false;;
    --)  shift; break;;
    -*)
      echo >&2 "usage: $0 [-v] [--out=<path to directory>] [--no-cache]"
      exit 1;;
    *)  break;;
    esac
    shift
done

Variables

Check if variable is set

if [ -n ${OUTDIR+x} ]; then
  echo "OUTDIR variable is set"
fi

Check if variable is not set or is empty

if [ -z ${OUTDIR+x} ] || [ "$OUTDIR" = "" ]; then
  echo "OUTDIR variable is not set or is empty"
fi