87

What is current directory of shell script? I this current directory from which I called it? Or this directory where script located?

Suzan Cioc
  • 27,971
  • 54
  • 206
  • 370
  • See also [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory) which is superficially about Python but also relevant here. – tripleee Apr 13 '22 at 06:29

5 Answers5

169

As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's installed location, it's quite simple. Below is a snippet that will print the PWD and the installed directory:

#!/bin/bash
echo "Script executed from: ${PWD}"

BASEDIR=$(dirname $0)
echo "Script location: ${BASEDIR}"
β.εηοιτ.βε
  • 24,064
  • 11
  • 54
  • 67
krg
  • 2,308
  • 2
  • 11
  • 9
  • This doesn't work for me. It only gives the name of the containing dir, not the full path. For example, if I do that from a script in `/home/user/scripts/x.sh`, it returns `scripts`, not `/home/user/scripts`. – Synchro Feb 08 '22 at 10:08
  • I think this is because your current working directory is `/home/user` and you called the script by `scripts/x.sh`. Hence, `$0` value inside the script is `scripts/x.sh`. In order to get the absolute path of the script, you can use `BASEDIR=$(cd $(dirname $0) && pwd)` – mnabil Mar 18 '22 at 11:12
55

Most answers get you the current path and are context sensitive. In order to run your script from any directory, use the below snippet.

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

By switching directories in a subshell, we can then call pwd and get the correct path of the script regardless of context.

You can then use $DIR as "$DIR/path/to/file"

saada
  • 2,452
  • 3
  • 25
  • 32
  • Can you explain what's going on? When my script gets run more than 20 times simultaneously, I get the following error: `....sh: fork: retry: Resource temporarily unavailable` The script gets run by OpenVPN. (under nogroup group and nobody account) – HosseyNJF Mar 25 '20 at 13:27
20

The current(initial) directory of shell script is the directory from which you have called the script.

ganesshkumar
  • 1,237
  • 1
  • 16
  • 34
8

You could do this yourself by checking the output from pwd when running it. This will print the directory you are currently in. Not the script.

If your script does not switch directories, it'll print the directory you ran it from.

keyser
  • 18,349
  • 16
  • 58
  • 97
2

To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"
4b0
  • 20,627
  • 30
  • 92
  • 137