Solved Resolve the full path name of an 'sh' script

I run in trouble resolving the full path of an sh (not bash) script or better, I want an "universal" sh function that resolve a path. I always used the following code to resolve a script path and always worked:
Bash:
sScriptDir="$( realpath $( dirname $0 ) )
it works. Now I symlinked the script (relative symlink) in another directory. The directory of the symlink is /linkdir, the script is in the directory linkdir/scripts (names are fictional)
Code:
cd /linkdir
ln -s ./scripts/myscript.sh myscript
now the code line above no more works, I have to do
Bash:
s1="$( realpath $( dirname $0 ) )"
s2="${s1}/$( readlink $0 )"
s3="$( realpath $s2 )"
# show result
echo "\$s1 '${s1}'"
echo "\$s2 '${s2}'"
echo "real:     '${s3}'"

I'm looking for a solution for absolute and relative symlinks

EDIT
An "universal" function for symlinks (relative and absolute) and real path (not symlinked)
 
If the link can be hardlink instead of symlink, can't your issue resolved?
(Need to be in the same filesystem, though.)

Quick test with the simple script below as /tmp/test.sh and set executable:
sh:
#!/bin/sh

echo $0
realpath $0
readlink -f $0

In case the link is symlink /tmp/test/test.sh
Code:
% ./test.sh    # at /tmp
./test.sh
/tmp/test.sh
/tmp/test.sh
% ./test.sh    # at /tmp/test
./test.sh
/tmp/test.sh
/tmp/test.sh
%

In case the link is hardlink /tmp/test/test.sh
Code:
% ./test.sh     # at /tmp
./test.sh
/tmp/test.sh
/tmp/test.sh
% ./test.sh     # at /tmp/test
./test.sh
/tmp/test/test.sh
/tmp/test/test.sh
%
 
basedir=$( dirname $(realpath $(readlink -f $0)))

Code:
dice@maelcum:~/test % ll
total 1
drwxr-xr-x  2 dice dice  3 Aug 20 14:43 scripts/
lrwxr-xr-x  1 dice dice 17 Aug 20 14:38 test@ -> ./scripts/test.sh
dice@maelcum:~/test % cat scripts/test.sh
#!/bin/sh

basedir=$( dirname $(realpath $(readlink -f $0)))

echo "$basedir"

echo "Hello World!"
dice@maelcum:~/test % ./test
/usr/home/dice/test/scripts
Hello World!
dice@maelcum:~/test % scripts/test.sh
/usr/home/dice/test/scripts
Hello World!

Doesn't work for hard-links though
Code:
dice@maelcum:~/test % ln ./scripts/test.sh hard_test
dice@maelcum:~/test % ./hard_test
/usr/home/dice/test
Hello World!
 
Great. I only need symlinks and no links. Many thanks to T-Aoki and SirDice for the solution. I spent all the morning to try to get a solution, the search point me to readlink, but info stated that only GNU tools and not in BSD, but a quick whereis readlink show it is in base system. Thank you all
 
Back
Top