Can a bash script figure out the full pathname to itself?
Yeah, but it needs help. Here’s a script demonstrating a technique I just developed.
#!/bin/bash
#
#--------------------------------------------------------------------------
#
# Written 2008-10-01 by mike@diehn.net.
#
# Demonstrates a technique for acquiring the full pathname of a
# script from within the script itself, using only shell
# features. I also show how to get just the parent directory
# name from that result, again using only shell features.
#
# $0 contains the name of the script as it was invoked.
#
# $PWD always contains the full pathname of the current
# working directory. What you get if you typed "pwd"
# and pressed
#
# When a bash script is invoked, these are the possible formats
# for the contents of $0:
#
# /full/path/to/scriptname
# relative/path/to/scriptname
# ./rel/path/to/scriptname
# ./scriptname
# scriptname
#
#--------------------------------------------------------------------------
# First, build the full pathname to this script.
#
case "$0" in
/* ) MyFullPathName="$0" ;;
./* ) MyFullPathName="$PWD/${0#./}" ;;
*/* ) MyFullPathName="$PWD/$0" ;;
* ) echo Whoopssss; exit 1 ;;
esac
MyDir=${MyFullPathName%/*}
MyName=${MyFullPathName##*/}
date
echo $MyFullPathName
echo $MyDir
echo $MyName