Bash For-Loop on Directories
No need for forking an external process:
echo "${i##*/}"
It uses the “remove the longest matching prefix” parameter expansion. The */
is the pattern, so it will delete everything from the beginning of the string up to and including the last slash. If there is no slash in the value of $i
, then it is the same as "$i"
.
This particular parameter expansion is specified in POSIX and is part of the legacy of the original Bourne shell. It is supported in all Bourne-like shells (sh, ash, dash, ksh, bash, zsh, etc.). Many of the feature-rich shells (e.g. ksh, bash, and zsh) have other expansions that can handle even more without involving external processes.