brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: realpath resolves a path and can print it relative to another folder

Linux
~/tips/tip-shell-realpath-relative-to

realpath ../../data/./file.txt

Turns a messy path with dots and symlinks into a clean absolute path, or one relative to a folder.

Scripts get paths like ../../data/./file and then something breaks because nobody knows what they point to. realpath cleans that up.

realpath ../../data/./file.txt

It prints the canonical name of the file: an absolute path without extra slashes, without . or .. parts and without symbolic links. The GNU manual calls it the preferred tool for this, with readlink -f as the older option that overlaps.

The option I use less often but like more is --relative-to. From /usr/bin, the command realpath --relative-to=/usr/bin /usr/bin/ /tmp/foo prints . and ../../tmp/foo. That is exactly what you need to build a relative symlink target.

ln -s "$(realpath -m --relative-to=/srv/site/current /srv/site/shared/uploads)" /srv/site/current/uploads

The -m flag means the path does not have to exist yet, and -e demands that every part exists. By default all but the last part must exist.

One caveat: --relative-to only gives a relative result when the other path is below something you named. When you also pass --relative-base, names outside that base are printed absolute. On macOS the system realpath is more limited, so GNU coreutils may be needed for these options. Check realpath --help on your system before you rely on a flag in a script that has to run on both.

Further reading: GNU Coreutils: realpath invocation, Realpath usage examples

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link