Wrong working directory, if bash script is opened via double-click I wrote a bash script in order to directly start eclipse from different workplace locations. Each workplace contains the script, after running it, eclipse is started with the respective workspace set.

#!/bin/bash

# relative path
#ECLIPSE_DIR='../../'
ECLIPSE_DIR='/Users/mike/Development/java/'
ECLIPSE="${ECLIPSE_DIR}eclipse/eclipse.app"

AUTHOR='mike'

# current directory is workspace
WORKSPACE=`pwd`
echo "WORKSPACE = $WORKSPACE"

# start eclipse from current directory
#open -n $ECLIPSE --args -data $WORKSPACE -vmargs -Duser.name='$AUTHOR'


The script is working, when I run it from the terminal. But when I double-click it, it uses the home directory as working directory and thus starts eclipse not from the directory that contains the script.

Apparently scripts are executed from ~/., which is the cause for my trouble. What can I do to fix this? Or how can I change my script to get the desired behavior?
If your script is stored at ~/workspaces/myproject/launch.sh and you want to be in that directory when you run, change to that directory, you can get the directory where the script is saved with this one liner:

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )


So the first few lines of your script become:

#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )
cd "${DIR}"
...the rest of your script...


This will put you in the directory where the script is stored no matter how your run the script.

If you want to learn more about detecting the location on disk of a script at execute time see this excellent StackOverflow answer.