So recently while working on some ansible automation, and in my testing container I realized I created by hand a symbolic link I could not remember. By hand I mean I did not automate the creation inside an ansible task.

So I had to find a way to list all symbolic links matching a given name for the binary I was looking for.

ls -la to the rescue.

So how to grab all the symbolic links under the /usr/bin directory (that is actually istself symlinked by /bin directory)

ls -la /usr/bin/ | grep "\->"

This returns all symbolic links, so we need to pipe (|) them once again

ls -la /usr/bin/ | grep "\->" | grep pgsql

Resulting in

lrwxrwxrwx 1 root root        37 Apr  5 17:34 pg_basebackup -> /etc/alternatives/pgsql-pg_basebackup

STOP and read below

Ok, that’s fine.. however on my searches on how to accomplish the way to find all symbolic links, I also stumbled upon

Why you shouldn’t parse the output of ls(1)

Don’t use grep to parse your ls -la command

Fortunately for me in this case the file name contained no special special new line character and such, otherwise the ls parsing command would have output something like this if the name was actually pgsql-\npg_basebackup and I would be running the output of the ls command to automate other parts of my provisioning step.(BAD IDEA)

$ ls -la /usr/bin/ | grep "\->" | grep pgsql
total X
-rw-r-----  1 root  root  37 Apr 5 17:34 pgsql- -> etc/alternatives/pgsql-\npg_basebackup
-rw-r-----  1 root  root   0 Apr 5 17:34 pgsql-?npg_basebackup -> etc/alternatives/pgsql-\npg_basebackup
-rw-r-----  1 root  root   0 Apr 5 17:34 pgsql- npg_basebackup -> etc/alternatives/pgsql-\npg_basebackup

Or similar, as this is just to show the possible output, all variable and based on the OS and pipe filter used

So how to correctly find all symbolic links for a given folder.

Using find and passing on type argument

find /usr/bin -type l -ls | grep pgsql

What about everywhere in the system?

find / -type l -ls | grep pgsql

And that’s it, yet another trivial (but not for me) task. Thank you for reading

André Ilhicas dos Santos

Devops Padawan, curious about systems automation, learning new languages, paradigms tools each day.

ilhicas ilhicas


Published