Hello,

I've a script that is launched with a soft link. Inside the script, I need to know where is the script, and I'm using the following :

SH_DIR = $(cd $(dirname "$0"); pwd)

But SH_DIR contains the path of the soft link

i.e, I've the soft link like this :

Deb:~# ls -l /etc/rc2.d/
lrwxrwxrwx 1 root root  27 2002-01-01 01:03 S99launch -> /usr/local/soft/bin/doit.sh

Inside doit.sh, SH_DIR contains /etc/rc2.d/ but I need /usr/local/soft/bin

Any ideas?

thanks!

Recommended Answers

All 3 Replies

That was kinda fun. There are two things to know:

  1. $BASH_SOURCE is the path to the currently executing script, as it was invoked; regardless of whether the script is executed or sourced. (actually the value is in ${BASH_SOURCE[0]} but the zero'th element of a bash array is available as the value of the variable itself) This is better than using $0.
  2. If the shell utility readlink gives you back the target of a symbolic link.

I was reminded of BASH_SOURCE by reading about the same question at Stack Overflow. Unfortunately, the script there didn't work for me, so I rolled my own: Here's a script that calculates and prints the directory where the ultimate target of a (chain of) symbolic link(s)

#!/bin/bash
_script_dir=$(dirname "$BASH_SOURCE")
_script=$(basename "$BASH_SOURCE")
pushd . > /dev/null
cd $_script_dir > /dev/null
while [ -h "$_script" ] ; do
  _script_dir=$(readlink "${_script}")
  cd $(dirname $_script_dir)
  _script=$(basename $_script_dir)
done
_script_dir=$(pwd)
popd > /dev/null
echo "I am located in $_script_dir"

Enjoy!

If you need to know where the script is, there is something wrong with your algorithm. Scripts should be in a directory in your PATH, and you should never need to know where it is.

If you need to know where the script is, there is something wrong with your algorithm. Scripts should be in a directory in your PATH, and you should never need to know where it is.

It is easy to make a general statement that is generally true... but much harder to make a general statement that is always true. I believe your statement is in the first category: I've needed to know 'where am i' when writing scripts more than once, though not usually.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.