Maybe you would like to 'factorize' this source code, in a dedicated common GNU/Bash script?
First, I think you may use the which command which is available on most of GNU operating system (often without additional installation)
https://savannah.gnu.org/projects/which/
Then you can create a 'common functionalities' file containing the source code you use to define the complete path, including symbolic link management, let's call it /tmp/myTrueDir/common.sh:
#!/bin/bash
set -e
# Usage: retrieveCompleteAbsolutePathresolveCompleteAbsolutePath <$0 path to regard>
function retrieveCompleteAbsolutePathresolveCompleteAbsolutePath() {
local _pathToManage="$1"
SOURCE="$_pathToManage"SOURCE="$1"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null && pwd )"
echo "$DIR"
}
Then you may use this at the beginning of all your little scripts (first we don't care having to manage symbolic links to reach the common.sh file which is in the same directory of your scripts)
currentDir=$( dirname "$( which "$0" )" )
source "$currentDir/common.sh"
Eventually, you can use the retrieveCompleteAbsolutePathresolveCompleteAbsolutePath function (defined in your common.shcommon.sh file), to get the complete path, including symbolic links resolution.
Such a way, your script will only contain the interesting source code you want, and the path management will be factorized in the same place.
For instance, you can easily test all this with this file system structure:
/tmp/myTrueDir/
/tmp/myTrueDir/common.sh
/tmp/myTrueDir/test.sh
With /tmp/myTrueDir/test.sh file having these sample lines:
#!/bin/bash
currentDir=$( dirname "$( which "$0" )" )
source "$currentDir/common.sh"
completeDir=$resolvedPath=$( retrieveCompleteAbsolutePathresolveCompleteAbsolutePath "$0" )
echo "currentDir: $currentDir"
echo "resolvedDir"resolvedPath: $completeDir"$resolvedPath"
Then you can create a symbolic link to your true directory, let's say:
ln -s /tmp/myTrueDir /tmp/mySymbDir
Then you can call your test script from the symbolic path (i.e. /tmp/mySymbDir/test.sh), and see it works like you want:
currentDir: /tmp/mySymbDir
resolvedDir: /tmp/myTrueDir