8

So I'm learning some bash and I'm trying to figure out how to get the directory a script is run from. So given that I have my script ~/scripts/bash/myscript, if I execute my scipt like:

user@localhost ~/dir/I/need/to/run/the/script/from $ ~/scripts/bash/myscript

from within my script, how can I get the directory from which it's being executed, so that I get ~/dir/I/need/to/run/the/script/from in this case. Shortcuts like:

DIR=`pwd`
DIR="$(cd "$(dirname "$0")" && pwd)"
DIR=`dirname $0`

as far as I can notice, they all assign the path to the script to DIR, but I'm looking for the path the script was run from.

Any help on this?

Thanks!! :)

5
  • 1
    pwd should work. Just be sure to call it early enough before you do any cd. Commented May 12, 2014 at 15:12
  • isn't this to get the path to the script itself? what I need is MY current directory, not the script's. if not, can you please point me how to get MY directory with readlink? thx Commented May 12, 2014 at 15:21
  • You are looking for the term current working directory, this "directory a script is run from" thing is vague and ill-defined. Commented May 12, 2014 at 15:33
  • "I need is MY current directory". Current working directory is defined for processes, not people or anyrhing else. Which process do you mean when you say "my"? Commented May 12, 2014 at 15:52
  • OK, my bad, sorry for the wording. As I said, I'm learning, thanks for pointing it out :) Commented May 12, 2014 at 16:00

1 Answer 1

14

The $PWD variable is probably what you need.

$ cat >/tmp/pwd.bash <<'END'
#!/bin/bash
echo "\$0=$0"
echo "\$PWD=$PWD"
END

$ chmod u+x /tmp/pwd.bash

$ pwd
/home/jackman

$ /tmp/pwd.bash
$0=/tmp/pwd.bash
$PWD=/home/jackman
Sign up to request clarification or add additional context in comments.

1 Comment

You can do this: scriptdir=$(dirname -- "$(realpath -- "$0")")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.