Say I have a symbolic link:


Say I have a shell variable x=/path/to/foo, how can I get some_file.txt in a shell variable y?


In zsh,


would expand to the tail of the absolute path of $x. So it would be some_file.txt unless some_file.txt is itself a symlink to something else.

Otherwise, you can use zsh zstat builtin:

zmodload zsh/zstat
zstat -A y +link -- $x && y=$y:t
| improve this answer | |

You can use readlink to get the pathname of the target file and then basename to extract its filename:

y="$(basename -- "$(readlink -- "$x")")"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.