1

Is it possible to run a shell script from any directory but the script keeps the directory context of where it is stored.

for example:

/projects/a/bin/myscript.sh

in projects/a i have:

- app
- code
- tmp
- bin
    - myscript.sh

myscript sets up some things in the projects app and code directories.

I want to be able to run setup from anywhere i.e. :

./bin/setup.sh

or directly within the bin directory:

./setup.sh

but the context seems to be taken from where the script is run from and not where the file is located.

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200
  • possible duplicate of [Can a Bash script tell what directory it's stored in?](http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in) – Organic Advocate Jun 18 '14 at 21:34

2 Answers2

3

The path to the script can be found in $0. That includes the script name itself, so you need to do something like

bin=$(dirname -- "$0")

Than you can either:

  • simply refer to the other scripts using that variable, like:

    . "$bin/utils.sh"
    "$bin/../app/app"
    

    etc.

  • enter the directory; but this breaks paths you've got on command-line unless you've made them absolute:

    cd "$bin"
    

Remember to quote properly!

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • +1. Or you can cd to that directory and work with relative paths from there: `cd -- "$(dirname -- "$0")"` – glenn jackman Oct 01 '13 at 12:22
  • @glennjackman: That's what you get when you combine the first and last line into one, yes. Just keep in mind that if the script takes any filename arguments, the user expects them to be relative to current directory when they run the script, so you have to change them to absolute paths (`readlink -f` is good for that, but it is not core tool and does not have to be installed everywhere) if you want to change directory inside the script. – Jan Hudec Oct 01 '13 at 13:06
0

You can get the script directory like this :

SCRIPTDIR=`dirname "$0"`

Then you can do

cd "$SCRIPTDIR"

in order to have the rest of your script run as if it was launched from its location. Your location won't be changed, only the executed script's one.

Alternatively, you can simply use $SCRIPTDIR in your commands.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758