Bash 遍历目录

Use a for loop:

for d in $(find /path/to/dir -maxdepth 1 -type d)
do
  #Do something, the directory is accessible with $d:
  echo $d
done >output_file
It searches only the subdirectories of the directory /path/to/dir. Note that the simple example above will fail if the directory names contain whitespace or special characters. A safer approach is:

find /tmp -maxdepth 1 -type d -print0 |
  while IFS= read -rd '' dir; do echo "$dir"; done
Or in plain bash:

for d in /path/to/dir/*; do
  if [ -d "$d" ]; then
    echo "$d"
  fi
done
(note that contrary to find that one also considers symlinks to directories and excludes hidden ones)

 

 

参考:

https://unix.stackexchange.com/questions/187167/traverse-all-subdirectories-in-and-do-something-in-unix-shell-script

posted @ 2020-09-01 11:22  wolbo  阅读(382)  评论(0编辑  收藏  举报