0

I would like to get the absolute path to an executed script. Its path is /use/local/lib/debugger.sh. And it is called through $PATH=/use/local/lib from another folder. I searched an example script and found following one.

echo "path = $(cd $(dirname $0) && pwd)"

I expected I can get the absolute path, /use/local/lib. But the result was not what I expected. I got the absolute path to the directory where the script is called.

How can I get the absolute path where the script exist?

Thank you very much.

mora
  • 2,217
  • 4
  • 22
  • 32

3 Answers3

2

Adding the -P option to pwd would make sure symlinks (if any) in the dirname of the script are properly resolved:

path=$(cd $(dirname $0) && pwd -P)
codeforester
  • 39,467
  • 16
  • 112
  • 140
1

Use this:

#!/bin/bash

path="path = $(cd $(dirname $0) && pwd)"
script_name="${0##*/}"

echo "${path}/${script_name}"

Or in "oneliner" style echo "path = $(cd $(dirname $0) && pwd)/${0##*/}"

OscarAkaElvis
  • 5,384
  • 4
  • 27
  • 51
1

If it is really in your $PATH then the "which" command should find it.

ivanivan
  • 2,155
  • 2
  • 10
  • 11