# How do I find the directory you run the script?



## valsorym (Aug 16, 2011)

Hi all,
Help me, please

How do I find the directory you run the script?


```
#!/bin/sh
#
filename=`readlink -e "${0}"`
whereami=`dirname "${filename}"`
echo "${whereami}"
```

but, it is Linux way - it is do not work in FreeBSD.


```
#!/bin/sh
#
whereami=`pwd`
echo "${whereami}"
```

I have: ~/scripts/test/run.sh

```
# cd ~/scripts/test/
# sh run.sh
[B]/usr/home/<USERNAME>/scripts/test/[/B]
```

It is Ok, but:

```
# cd ~/scripts/
# sh test/run.sh
[B]/usr/home/<USERNAME>/scripts/[/B]
```
It is not good!
This is understandable, the command "pwd" displays the path where the current terminal.

The script is in fact in  ~/scripts/test/.
Help me, please.


----------



## graudeejs (Aug 16, 2011)

```
dirname "$0"
```


----------



## valsorym (Aug 16, 2011)

```
#!/bin/sh
#
filename=`realpath "${0}"`
whereami=`dirname "${filename}"`
echo "${whereami}"
```
It is work, sorry for the empty air agitation.

Thank you all.


----------



## kpedersen (Aug 16, 2011)

```
CWD="`pwd`"
SCRIPT="`which $0`"
RELDIR="`dirname $SCRIPT`"
cd "$RELDIR"
DIR="`pwd`"
cd "$CWD"

echo $DIR
```

This looks a bit tacky but supports a couple of things such as...

1) Gets the dir even if the script was run from $PATH
2) Gets the dir even when the script is located below current path (../../../script)
3) Gets an absolute path from '/' rather than relative so is sometimes more compatible with whatever you plan to do with it.

I often use a similar idea to this with C++ to create software that can be run from anywhere (and find resources) rather than hard coding at build time. It generally works well but will fail if the directory below the script is not readable.

The important part is to cd into the required directory and *then* running pwd to get an absolute path.


----------



## valsorym (Aug 16, 2011)

Thanks all. Very much thanks.


----------

