9

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?

3
  • I thought scripts were run from /
    – mmmmmm
    Commented Mar 31, 2015 at 18:00
  • Why not eclipse up so when it starts it shows a list of workspaces and choose that one - I think you would need a Applescript to do this as you need to get the directory from Finder
    – mmmmmm
    Commented Mar 31, 2015 at 18:01
  • There is nothing in your script which would cd to the script directory. Actually, wanting a script to run with the working directory set to the script directory, is such an exotic requirement, that you can't really expect it to be the default. Commented May 27 at 10:07

1 Answer 1

12

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]}" )" && pwd )

So the first few lines of your script become:

#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && 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.

5
  • 1
    OP wants the directory of the workspace not the shell script
    – mmmmmm
    Commented Mar 31, 2015 at 18:02
  • 1
    @Mark The shell script is in the same directory. Thx, for the answer. I'll apply it, when I'm home again.
    – mike
    Commented Mar 31, 2015 at 18:11
  • But you need one of these for and in each workspace
    – mmmmmm
    Commented Mar 31, 2015 at 18:41
  • 1
    Yes, that was in the premiss I stated in my question :)
    – mike
    Commented Mar 31, 2015 at 21:01
  • @Mark, how would I go with the directory of the workspace? Commented Oct 18, 2018 at 16:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .