Get full directory path of a script regardless of where it is run from

STARTING_DIR=$(cd $(dirname $0) && pwd)
Sometimes you need the full path to your script, regardless of how it was executed (which starting directory) in order to maintain other relative paths in the script. If you attempt to just use something simple like: STARTING_DIR="${0%/*}" you will only get the relative path depending on where you first executed the script from. You can get the relative path to the script (from your starting point) by using dirname, but you actually have to change directories and print the working directory to get the absolute full path.
Sample Output
[bbbco@bbbco-dt scripts]$ vi startingdir.sh
-----------------
#!/bin/bash
echo $(cd $(dirname $0) && pwd)

-----------------

[bbbco@bbbco-dt scripts]$ ./startingdir.sh 
/home/bbbco/scripts
[bbbco@bbbco-dt scripts]$ cd ..
[bbbco@bbbco-dt ~]$ scripts/startingdir.sh 
/home/bbbco/scripts
[bbbco@bbbco-dt ~]$ cd Downloads/
[bbbco@bbbco-dt Downloads]$ /home/bbbco/scripts/startingdir.sh 
/home/bbbco/scripts
[bbbco@bbbco-dt Downloads]$ 

0
By: bbbco
2011-11-30 17:35:15

3 Alternatives + Submit Alt

What Others Think

consider perhaps: dirname $(readlink -f $0)
linuxrawkstar · 355 weeks and 5 days ago
If you add some quoting, you will get robust against spaces in directory names: cd "$(dirname "$0")" && pwd
f4m8 · 355 weeks and 5 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: