Skip to content

Instantly share code, notes, and snippets.

@mpdaugherty
Created May 14, 2012 03:11
Show Gist options
  • Save mpdaugherty/2691564 to your computer and use it in GitHub Desktop.
Save mpdaugherty/2691564 to your computer and use it in GitHub Desktop.
Get the containing directory of the currently executing shell script, regardless of whether it is called or sourced.
#!/bin/bash
# Temporarily save the old values so we can restore them after execution
SOURCE_TEMP=$SOURCE
DIR_TEMP=$DIR
SOURCE="${BASH_SOURCE[0]}"
# Go through all symlinks to find the ultimate location of the source file
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
# Get an absolute path to the directory that contains this file
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
###
# YOUR CODE HERE
###
# Restore old values
SOURCE=$SOURCE_TEMP
DIR=$DIR_TEMP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment