How to get the path to the script file inside the script when called via sym link

When I need to get the path to the script file inside the script, I use something like this:

`dirname $0` 

which works with the file until I call the script link through sym. In this case, the above code prints the location of the link instead of the source file.

Is there a way to get the path to the source script file and not the link?

Thanks Mike

+7
linux scripting bash
source share
5 answers
 if [ -L $0 ] ; then DIR=$(dirname $(readlink -f $0)) ; else DIR=$(dirname $0) ; fi ; 
+12
source share

You really need to read the following BashFAQ article:

In truth, the $0 hacks are NOT reliable, and they will fail when applications start with a null argument, which is not an application. For example, login(1) will put - in front of your application name at $0 , causing a breakdown, and whenever you call an application that in PATH $0 will not contain the path to your application, but just a file name, which means that you You cannot extract any location information from it. There are many ways in which this can fail.

Bottom line: don't rely on a hack, however, you cannot figure out where your script is located, so use the configuration parameter to set the directory of your configuration files or something else you need a script path for.

+14
source share

Use readlink for this:

 readlink -f "$0" 
+6
source share
 Dir=$(dirname $(readlink -f "$0")) 
+1
source share

I suggest the following:

 dirname $(realpath $0) 

Example:

 skaerst@test01-centos7:~/Documents> ../test/path.sh dirname realpath: /home/skaerst/test skaerst@test01-centos7:~/Documents> cat ../test/path.sh #!/bin/bash echo "dirname realpath: $(dirname $(realpath $0))" 

works with symbolic links because realpath uses -P by default:

 skaerst@test01-centos7:~/Documents> ln -s ../test/path.sh p skaerst@test01-centos7:~/Documents> ./p dirname realpath: /home/skaerst/test 

realpath is available with coreutils> 8.5, I think

 skaerst@test01-centos7:~/Documents> rpm -qf $(which realpath) $(which dirname) coreutils-8.22-15.el7_2.1.x86_64 coreutils-8.22-15.el7_2.1.x86_64 

Hth

Hi

Stephen

0
source share

All Articles