4

I have some script, that uses files in directories around it. It uses

dirname $0

command. It should work from any directory where I run this script, but when I run a symbolic link that points to that script I get the path of symbolic link. So I get the output of dirname rather than the path of the script itself.

Any one know a way to get the path of where the script is run?

benRollag
  • 1,219
  • 4
  • 16
  • 21
rodnower
  • 1,365
  • 3
  • 22
  • 30
  • possible duplicate of [Bash script: set current working directory to the directory of the script](http://stackoverflow.com/questions/3349105/bash-script-set-current-working-directory-to-the-directory-of-the-script) – mob Jul 30 '10 at 16:14
  • 1
    Also see [BashFAQ/028](http://mywiki.wooledge.org/BashFAQ/028). – Dennis Williamson Jul 30 '10 at 17:54

4 Answers4

4

Get the real path to your script

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)
jmz
  • 5,399
  • 27
  • 29
1

A simpler solution:

dirname $(readlink -f $0)

Tested with on Ubuntu 14.04: which java returns /usr/bin/java, which is a symbolic link.

readlink -f `which java`

Returns /usr/lib/jvm/java-8-oracle/jre/bin/java

Finally,

dirname $(readlink -f `which java`)

Returns /usr/lib/jvm/java-8-oracle/jre/bin, which is the folder under which "java" is located.

Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
0

if you have realpath installed:

$(dirname $(realpath $0))
knittl
  • 246,190
  • 53
  • 318
  • 364
0

Unless I misunderstand you, the problem should be the same as the one in: How do you normalize a file path in Bash?

An option not mentioned there is the following python one-liner:

python2.6 -c "import os,sys; print os.path.realpath(sys.argv[1])" "$0"

Finally, remember to use double quotes around "$0".

Community
  • 1
  • 1
loevborg
  • 1,774
  • 13
  • 18
  • The answer of jmz is what I need. I little afraid to use you suggestion, because the version of Python at the end of the command name may be different from server to server, and script will less portable. – rodnower Aug 02 '10 at 16:29
  • Oh that was a typo. Any recent version of python (starting at 2.2) should do, so you can just use "python" instead. – loevborg Aug 02 '10 at 20:16