Bash For-Loop on Directories Bash For-Loop on Directories shell shell

Bash For-Loop on Directories


Do this instead for the echo line:

 echo $(basename "$i")


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.


If you do a cd at the start of the script, it should be reverted when the script exits.

#!/bin/bashcd srcfor i in * ; do  if [ -d "$i" ]; then    echo "$i"  fidone