Bash modules

From wikinotes


Windows uses file-extensions to determine what program to use to open/run a program. Unix systems use mimetypes, which uses a combination of file-extensions, and signatures written within the file. This means that file-extensions are optional for bash-scripts.

Place this line at the top of your file to instruct your system that this file should be opened with an executable called bash. You can substitute this with something else, for example this might be a python, perl, or ruby script.

#!/usr/bin/env bash

Set bash options

See docs

  • -${flag} set option
  • +${flag} unset option
# some common bash script options
set -e            `# exit if any pipe/command fails` \
set -o  pipefail  `# pipe exitcode is last pipe in pipeline to exit w/ failure` \

See more documentation in bash configuration. </syntaxhighlight>

Name of Script

EXECUTABLE="$(basename ${BASH_SOURCE[0]})"  # bash
EXECUTABLE="$(basename "$ZSH_ARGZERO")"     # zsh

Finding Path of Running Bash Script

currentPath="`( cd \"$currentPath\" && pwd )`"


DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
## This works as long as you are not using a symbolic link. In the event that you
## are using a symbolic link:

while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

Commandline Arguments

See bash arguments .