Unix get final directory name in a symlink

I have symlinks in a directory full of versions that each point to a specific version. The file structure would look like this:

  • /path/to/stuff/v1
  • /path/to/stuff/v1.1
  • /path/to/stuff/v2
  • /path/to/stuff/v3
  • /path/to/stuff/A -> /path/to/stuff/v1.1
  • /path/to/stuff/B -> /path/to/stuff/v3

I need a way to get only the version number from a specific symlink (i.e for /path/to/stuff/A I want only "v1.1").

readlink gets the whole path: readlink /path/to/stuff/A = /path/to/stuff/v1.1

I've scoured other questions but nothing I've found has met these exact requirements yet


You can either use basename with command substitution (available in all POSIX shells, not only in Bash):

$ basename "$(readlink /path/to/stuff/A)"
v1.1

Or rev + cut:

$ readlink  /path/to/stuff/A | rev | cut -d/ -f1 | rev
v1.1