Sample Header Ad - 728x90

Apply readlink to a non-symlink file?

1 vote
2 answers
1653 views
This code from Stack Overflow is to get the pathname to the parent directory of a script inside the script, even if the script is run via a symlink to it: if [ -L $0 ] ; then DIR=$(dirname $(readlink -f $0)) ; else DIR=$(dirname $0) ; fi ; Is the above code equivalent to DIR=$(dirname $(readlink -f $0)) ; i.e. is there really a need to test if $0 is a symlink, and run different commands if yes and if no? Why not just use $(dirname $(readlink -f $0)) regardless of whether $0 contains symlink or not? Specifically, if $0 contains symlink, then it is perfect to use $(dirname $(readlink -f $0)). if $0 is not a symlink, then it seems perfect to me to just use $(dirname $(readlink -f $0)): - $(readlink -f $0) returns the absolute path of $0, and $(dirname $(readlink -f $0)) returns the absolute path to the parent directory of $0 - $(dirname $0) returns a path to the parent of $0, whether the return is an absolute or relative path depending on if $0 is an absolute or relative path. - I don't think whether the value of DIR is an absolute or relative path is important in the original code, because in either case, the value of DIR refers to the parent directory of $0. So are $(dirname $(readlink -f $0)) and $(dirname $0) equivalent in the original code? Thanks.
Asked by Tim (106430 rep)
Mar 21, 2018, 04:35 AM
Last activity: Jan 23, 2021, 10:12 AM