Useful Coreutils & Options
This is a small collection of specific scenarios involving coreutils, with options that I found particularly useful.
chown --reference
I use systemd-nspawn a lot for containerization.
Multiple times I ran into the inconvenience of having insufficient file permissions for a fs mount coming from the host.
See the following example:
My host bind-mounts /mnt/data/torrent to /var/lib/machines/torrent/home/qbtuser/Downloads.
root@torrent:/home/qbtuser/Downloads# ls -la
drwxr-xr-x 1 nobody nogroup 40 May 24 22:37 .
drwx------ 6 qbtuser qbtuser 4096 Apr 13 19:39 ..
drwxr-xr-x 1 qbtuser qbtuser 1100 May 22 23:14 excluded
However, the directory is not owned by any uid of the container users, not even root:
root@torrent:/home/qbtuser/Downloads# touch test
touch: cannot touch 'test': Permission denied
This fails, since root in the container and root on the host do not share the same uid (I configured PrivateUsers=pick).
Now I want to create another subdirectory, owned by the qbtuser, which only exist in the scope of the container.
Only the host has permission to do so, but the host does not know the qbtuser user.
So after creating a directory, how can ownership be transferred if qbtuser is unknown to the host?
This is where the --reference option of chown comes in handy.
It takes the user & group from an existing file and sets them as the new user & group of the target file.
root@host:/mnt/data/torrent# mkdir test
root@host:/mnt/data/torrent# chown --reference ./excluded ./test
root@torrent:/home/qbtuser/Downloads# ls -la
drwxr-xr-x 1 nobody nogroup 48 May 24 22:55 .
drwx------ 6 qbtuser qbtuser 4096 Apr 13 19:39 ..
drwxr-xr-x 1 qbtuser qbtuser 1100 May 22 23:14 excluded
drwxr-xr-x 1 qbtuser qbtuser 0 May 24 22:55 test
root@torrent:/home/qbtuser/Downloads# touch test/test # no more permission error, yay
chmod --reference
The --reference option also exists for the chmod utility.
I use it sometimes to fix the permissions of an imported ssh key, by taking a “known good one” as a reference:
[sandro@arch ~/.ssh]$ chmod --reference=id_ed25519 ./imported 130
realpath -s
pwd is a well-known utility to print the current directory path.
I searched its man-page in hope to find a parameter option of passing a target file such that the program would return the path to this file.
This functionality houses in another program: realpath. The option -s tells the program not to unwrap symlinks.
sandro@nas:/etc/nginx/sites-enabled$ realpath default
/etc/nginx/sites-available/default
sandro@nas:/etc/nginx/sites-enabled$ realpath -s default
/etc/nginx/sites-enabled/default
I find myself using realpath a lot for copying a path to the clipboard:
$ realpath -s ./image.png | xclip -selection clipboard # on X.org
$ realpath -s ./image.png | wl-copy # on wayland
…resulting in /home/sandro/image.png being the content of my clipboard.