Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Last active April 17, 2017 15:23
Show Gist options
  • Save JayGoldberg/38d5da8502c6750a5b0ee68878861e38 to your computer and use it in GitHub Desktop.
Save JayGoldberg/38d5da8502c6750a5b0ee68878861e38 to your computer and use it in GitHub Desktop.
Is the file in question a soft or hard link to this other file?
#!/bin/sh
## @author Jay Goldberg
## @email jaymgoldberg@gmail.com
## @license Apache 2.0
## @description Determine if a file is a symlink or hardlink to a particular file
## Example, "is this file a hard or softlink to Busybox?
## @usage source it, then IsLinked <possible_link> <target>
#=======================================================================
IsLinked() {
# TODO what if `which` doesn't exist? `which` is actually a shell script
[ ! "$#" -eq 2 ] && { echo "wrong argument count" >&2; return 4; }
local destexe="$(which $2)"
local exe="$(which $1)"
[ ! -f "$destexe" ] || [ ! -e "$exe" ] && { echo "some of the paths do not exist" >&2; return 1; }
# is $exe a symlink?, if so, is it pointing to $destexe?
if [ -L "$exe" ] && [ "$(basename $(readlink $exe))" = "$(basename $destexe)" ]; then
echo "true"
# is it a hardlink to $destexe?
# TODO: what if `stat` is not available? (ls -i $exe | cut -d' ' -f1)
elif [ "$(stat -c %i $exe)" = "$(stat -c %i $destexe)" ]; then
echo "true"
else
echo "false"
fi
}
_Test_IsLinked() {
local EXITCODE=0
local destexepath="ls_target"
local sourceexe="ls_link"
touch "$destexepath" || { echo "unable to create test target"; return 1; }
chmod u+x "$destexepath" || { echo "unable to mark test target as executable"; return 1; }
export PATH="./:$PATH"
rmfiles() { [ -e "$sourceexe" ] && rm "$sourceexe"; }; rmfiles
echo "create softlink"
ln -s "$destexepath" "$sourceexe" || { echo "unable to create softlink"; return 1; }
echo " >>> is it a softlink?"
[ $(IsLinked "$sourceexe" "$destexepath") == "true" ] && echo "PASS"
rmfiles
echo "create hardlink"
ln "$destexepath" "$sourceexe" || { echo "unable to create hardlink"; return 1; }
echo " >>> is it a hardlink?"
[ $(IsLinked "$sourceexe" "$destexepath") == "true" ] && echo "PASS"
rmfiles
touch "$sourceexe"
echo "bogus link?"
IsLinked "$sourceexe" "$destexepath" || echo "PASS"
rmfiles
rm "$destexepath" || echo "unable to delete test file"
return $EXITCODE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment