How do I find the directory you run the script?

Hi all,
Help me, please

How do I find the directory you run the script?

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

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

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

I have: ~/scripts/test/run.sh
Code:
# cd ~/scripts/test/
# sh run.sh
[B]/usr/home/<USERNAME>/scripts/test/[/B]

It is Ok, but:
Code:
# 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.
 
Code:
#!/bin/sh
#
filename=`realpath "${0}"`
whereami=`dirname "${filename}"`
echo "${whereami}"
It is work, sorry for the empty air agitation.

Thank you all.
 
Code:
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.
 
Back
Top