Issue
How many times have you had to go to a specific directory to launch an application or set several environment variables for an application to be able to find itself and run? Well, here’s a simple trick to add to your shell scripts so that they’re self-contained with no external requirements or editing.
Trick
Put the following code in the top of your scripts and they’ll set your working directory to the directory in which the script actually resides. This way, you’ll have a known base directory from which to call any other commands. This also makes your launch scripts portable to other systems and directory structures without having to edit them to set a new directory or add new environment variables.
For *nix platforms: (this works in sh and bash)
#Get the fully qualified path to the script case $0 in /*) SCRIPT="$0" ;; *) PWD=`pwd` SCRIPT="$PWD/$0" ;; esac # Resolve the true real path without any sym links. CHANGED=true while [ "X$CHANGED" != "X" ] do # Change spaces to ":" so the tokens can be parsed. SCRIPT=`echo $SCRIPT | sed -e 's; ;:;g'` # Get the real path to this script, resolving any symbolic links TOKENS=`echo $SCRIPT | sed -e 's;/; ;g'` REALPATH= for C in $TOKENS; do REALPATH="$REALPATH/$C" while [ -h "$REALPATH" ] ; do LS="`ls -ld "$REALPATH"`" LINK="`expr "$LS" : '.*-> (.*)$'`" if expr "$LINK" : '/.*' > /dev/null; then REALPATH="$LINK" else REALPATH="`dirname "$REALPATH"`""/$LINK" fi done done if [ "$REALPATH" = "$SCRIPT" ] then CHANGED="" else SCRIPT="$REALPATH" fi done # Change ":" chars back to spaces. REALPATH=`echo $REALPATH | sed -e 's;:; ;g'` # Change the current directory to the location of the script cd "`dirname "$REALPATH"`"
For Windows platforms:
Surprisingly, for Windows DOS there’s a much easier way to do this — just add the following to the top of your batch file.
cd %~dp0%
Happy scripting!











