Most of the posted answers are not robust on URLs that contain query strings or targets, such as, for example, the following:
Python has URL parsing in its standard library; it's easier to let it do it. E.g.,
from urllib import parse
path = parse.urlparse(sys.stdin.read().strip()).path
print("/" if not path or path == "/" else path.rsplit("/", 1)[-1])
You can compact that into a single
python3 -c for use in a shell script:
echo 'https://example.com/this/is/a/path/componets?query#target' \
| python3 -c 'from urllib import parse; import sys; path = parse.urlparse(sys.stdin.read().strip()).path; print("/" if not path or path == "/" else path.rsplit("/", 1)[-1])'
(You can also keep the script broken out, too, for readability.
' will let you put newlines in.)
Of course, now your shell script has a dependency on Python.
(I'm a little unsure about the if that tries to handle cases where the URL's path component is the root (
/); adjust/test if that matters to you.)