Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a script doSmth in /usr/bin. Is it possible to print the directory the script was called from is printed out by the script?

So If I call doSmth from /home/me the output will be /home/me.

share|improve this question
In what language? – jordanm Oct 25 '12 at 20:43
Uhh, in bash :) – Primož Kralj Oct 25 '12 at 20:44
Tried it now and it works as expected! – Primož Kralj Oct 25 '12 at 20:52
up vote 5 down vote accepted

When you invoke a command in the shell, the new process inherits the working directory of the parent. Here are two ways get the working directory:

echo "$PWD" # variable
pwd         # builtin command
share|improve this answer
Thank you, I couldn't find this via Googling. – Primož Kralj Oct 25 '12 at 20:51

By "directory it was called from" you seem to mean its working directory. You can change this inside the script using e.g., cd, but before you do so, pwd will print it out. It'll also likely be in the variable $PWD

If you'll need the initial working directory after changing it, just save it at the top of your script (before changing it)


# ... do a lot of stuff ...
# ⋮

cd "$initial_wd"

If you're using this to get back to the directory you started in, see also pushd and popd.

share|improve this answer
In bash, there is also "$OLDPWD". – jordanm Oct 25 '12 at 20:48
@jordanm Indeed there is, but that won't necessarily be the initial working directory (e.g., if you've used cd twice) – derobert Oct 25 '12 at 20:50
Thanks for the answer and great additional explanation. – Primož Kralj Oct 25 '12 at 20:52
$OLDPWD is what I need; I run bash scripts from the CMD Prompt on Win7 and this was the environment variable that held the directory I run the script from. Cheers – Darren Bishop Nov 27 '13 at 11:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.