Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

2 Answers

up vote 2 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
add comment

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)

#!/bin/bash
initial_wd=`pwd`

# ... 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
2  
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 Nov 27 '13 at 11:00
add comment

Your Answer

 
discard

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.