Skip to content

Instantly share code, notes, and snippets.

@eezing
Last active August 1, 2018 18:02
Show Gist options
  • Save eezing/d43f8ed871e2adcd600a7bb1a2a5a48d to your computer and use it in GitHub Desktop.
Save eezing/d43f8ed871e2adcd600a7bb1a2a5a48d to your computer and use it in GitHub Desktop.

Bash Notes

Notes, code snippets for Bash.

Offical Docs

Snippets

isEmpty function

Is argument set or empty string.

function isEmpty() {
  local target=$1
  if [ -z "$target" -a "${target+xxx}" = "xxx" ]; then 
    echo true
  else
    echo false
  fi
}
Example
foo="bar"
isEmpty $foo # --> false

foo=""
isEmpty $foo # --> true

Parse option arguments

# Do something for arg 'a' and 'b'.
# Ex: $ bash [my-file.sh] -a hello -b world
# --> hello
# --> world

while getopts ":a:b:" opt; do
  case ${opt} in
    a )
      target=$OPTARG
      echo $target
      ;;
    b )
      target=$OPTARG
      echo $target
      ;;
    \? )
      echo "Invalid option: $OPTARG" 1>&2
      ;;
    : )
      echo "Invalid option: $OPTARG requires an argument" 1>&2
      ;;
  esac
done
shift $((OPTIND -1))

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