Skip to content

Instantly share code, notes, and snippets.

@ShannonScott
Last active February 24, 2020 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShannonScott/e225027e7b3074f151d8052448255408 to your computer and use it in GitHub Desktop.
Save ShannonScott/e225027e7b3074f151d8052448255408 to your computer and use it in GitHub Desktop.
[Bash Notes] General notes on using and scripting Bash. #tags: bash, notes

Bash Notes

General notes on using and scripting Bash.

Argument parsing

Here's a nice article on the topic of argument parsing in Bash: Bash: Argument Parsing

From the article:

#!/bin/bash
PARAMS=""
while (( "$#" )); do
  case "$1" in
    -f|--flag-with-argument)
      FARG=$2
      shift 2
      ;;
    --) # end argument parsing
      shift
      break
      ;;
    -*|--*=) # unsupported flags
      echo "Error: Unsupported flag $1" >&2
      exit 1
      ;;
    *) # preserve positional arguments
      PARAMS="$PARAMS $1"
      shift
      ;;
  esac
done
# set positional arguments in their proper place
eval set -- "$PARAMS"

Another look at argument parsing

Inspired by the first script found here: Updated Pi Zero Gadgets

A nice explanation of the variable expansion being used: variable expansion in curly braces

Example

#!/bin/bash
op="${1?Must specify op}"
mac="${2:-mac}"
ip="${3:-ip}"
host="${4}"

echo $op
echo $mac
echo $ip
echo $host

Boolean variables in Bash

How can I declare and use Boolean variables in a shell script?

Switch on current operating system

A nice example from: dotfiles/zsh/.zshrc

case `uname` in
  Darwin)
    source $HOME/.zshrc-mac
  ;;
  Linux)
    source $HOME/.zshrc-linux
  ;;
  FreeBSD)
    # commands for FreeBSD go here
  ;;
esac

Timestamps

outfilename="db.$(date +%Y%m%d_%H%M%S).csv.gz"

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment