Is there a non-recursive readlink -f
/ realpath
alternative, that outputs absolute symlink destinations? A more POSIX compatible solution is welcome as well.
I have a function block in my shell script as follows:
set FILES
# addFile adds a file to the FILES list. If file is a symlink,
# it will also find and add the destination.
addFile() {
file="$1"
# Check if file is already included in list
echo "$FILES" | grep -q "$file" && return
FILES="$FILES $file"
if [ -L $file ]; then
addFile $(realpath $file)
#addFile $(readlink $file)
fi
}
I'm using this function in a script which is collecting binary and library files from around the file system. But I foresee a problem in this code:
- My first try I used
readlink
, but this returned symlink resolution paths relative to the$file
, thus any actions performed on those paths fail. (Now commented out, but still in code) (See minor edit below) - After that, I used
realpath
instead, as suggested byman readlink
. It almost works.
Now, the actions that I want to perform can work. However, in the final result I'm copying over all the binaries, libraries and symlinks in an initramfs. If there are any recursive symlinks, only the top level and the destination will be included, not the intermediate ones. Thus, breaking the symlink.
I've created a fiddle to demonstrate the issue. link-to-link1
points to link1
, which points to file1
. In the end result link1
is missing and link-to-link1
is broken.
Edit; clarify the issue
When running the above function on the following set of symlinks:
# Contents of ~/test/src
file0
file1
link0 -> file0
link0.1 -> file0
link1 -> file1
link-to-link1 -> link1
With:
copy="link-to-link1 link0 link0.1"
for sf in $copy; do
addFile ~/test/src/$sf
done;
cp -av $FILES ~/test/dst
You will find that only the 3 links from $copy
and 2 files are copied. However, intermediate link link1
is missing and link-to-link1
is broken.
I would like the script to find link1
as well. Keeping in mind that in the environment where this script is run, the location of files and symlinks have to be absolute.
Minor edit
Add another fiddle to demonstrate failing of relative paths, using readlink
. Only the symlinks are copied and the destinations are missing.