After reading a couple posts on the subject, I came up with the compilation of all advice (that are supposed to work on any situation) and wrote the following script.
But tell me something... Is it that crazy that there's no other way to get the same solution!!!
this is a very hard problem. Period. There are many ways to invoke a script
Perderabo has a long discussion about this if you have not already seen the thread.
Consider: Do not use exec as a variable name - it is a builtin in bash.
Thx jim mcnamara for your answer,
1) I searched the forum for "perderabo path running script" but could not find the thread you're talking about
2) Thanks for the advice
Thank you radoulov.
$0 will only give me the path to the file as the user called it. If my script is in the PATH, the user will call it by it's bare name and I will not be able to know the full path to it. I will study $BASH_SOURCE. What do you mean by (bash >= 3 only)?
Thank you Scrutinizer.
Same explanation as above. If the user calls my script by its bare name, dirname $0 will output nothing.
Have you tried calling calling it "by it's bare name". If the script is somewhere in the search path then $0 should return the actual path to the script. Anyway, I a still not sure I understand what you mean. I think what you mean is to have a simple script that returns the absoute path to itself?
#!/bin/bash
echo $(cd $(dirname $0);pwd)
Should always do that I think..
If that is not what you mean could you state what you are looking for exactly?
~# cat /root/s
#!/bin/bash
echo "I'm a user created script stored in /root/"
which $0
~# cat /usr/local/bin/s
#!/bin/bash
echo "I'm a user created script stored in /usr/local/bin/"
which $0
~# bash s
I'm a user created script stored in /root/
/usr/local/bin/s
~# cat /usr/local/bin/s
#! /bin/sh
echo "I'm a user created script stored in /usr/local/bin/"
p="$(realpath "$0")"
printf "%s\n" "${p%/*}"
~# bash s
I'm a user created script stored in /usr/local/bin/
s: No such file or directory