Get directory from which script was called from

10,618

Solution 1

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

Solution 2

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:
10,618

Related videos on Youtube

c0dehunter
Author by

c0dehunter

Updated on September 18, 2022

Comments

  • c0dehunter
    c0dehunter almost 2 years

    I have a script doSmth in /usr/bin. Is it possible to get and print the directory the script was called from?

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

    • Admin
      Admin over 11 years
      In what language?
    • Admin
      Admin over 11 years
      Uhh, in bash :)
  • jordanm
    jordanm over 11 years
    In bash, there is also "$OLDPWD".
  • derobert
    derobert over 11 years
    @jordanm Indeed there is, but that won't necessarily be the initial working directory (e.g., if you've used cd twice)
  • Diego Nogueira
    Diego Nogueira over 10 years
    $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