bash - How to find only the destination of a softlink
This will get the destination of the soft-link (whether it's a file or directory) and return it.
Find only destination of symlink
Good answers in all, but had a problem with the first answer using readlink (by nikitautiu) as the version that macOS is using, doesn't have the same flags as what the system the top answer is using. Sigh.
The second answer worked on Mac and other systems, but it's not cross platform as well, from what I read, though it worked just fine. Indeed, this answer (from Coroos) gave many different ways to do what I needed.
The third answer, by Lea Gris (don't know how to do the special characters above the e and i) was what I ended up using, as I saw it (not sure if by same person or not, but same name of script function) elsewhere as well.
bash_realpath() {
# print the resolved path
# @params
# 1: the path to resolve
# @return
# &1: the resolved link path
local path="${1}"
while [[ -L ${path} && "$(ls -l "${path}")" =~ -\>\ (.*) ]]
do
path="${BASH_REMATCH[1]}"
done
echo "${path}"
}
I put it in my .mike/my_setup/bin directory as bash_realpath.sh with checking for correct parameters and the like, so it's callable from anywhere.
#!/usr/bin/env bash
#### ===================================================
#### scripts defined in this/these file(s)
source $(dirname "$0")/utils/colors.sh
source $(dirname "$0")/utils/xml_diff.sh
#### ===================================================
#### comment/uncomment for debugging
#### set -xv
#### set -e
#### ====================================================
#### got from the following
#### https://unix.stackexchange.com/questions/47710/find-only-destination-of-symlink
#### - Lea Gris
bash_realpath() {
# print the resolved path
# @params
# 1: the path to resolve
# @return
# &1: the resolved link path
local path="${1}"
while [[ -L ${path} && "$(ls -l "${path}")" =~ -\>\ (.*) ]]
do
path="${BASH_REMATCH[1]}"
done
echo "${path}"
}
#### ----------------------------------------------------
print_help_message() {
printf "\nHelp for $0 \n"
printf "\n"
printf "${YELLOW}$0${NC} ${GREEN}<path to soft-linked file>${NC}\n"
printf "\n"
}
#### ====================================================
#### ====================================================
#
#### start script
if [ "$#" -lt 1 ]; then
printf "\n${RED}Illegal number of parameters!${NC}"
print_help_message
exit 1
fi
#### call the function to do stuff
bash_realpath "$1"
It uses several other common script files that I'm using, so it's not complete as shown here, but all of the files are in my repo.