How to loop over directories in Linux?

2020-01-24 10:24发布

I am writing a script in bash on Linux and need to go through all subdirectory names in a given directory. How can I loop through these directories (and skip regular files)?

For example:
the given directory is /tmp/
it has the following subdirectories: /tmp/A, /tmp/B, /tmp/C

I want to retrieve A, B, C.

标签: linux bash
9条回答
一夜七次
2楼-- · 2020-01-24 11:07

a minimal bash loop you can build off of (based off ghostdog74 answer)

for dir in directory/*                                                     
do                                                                                 
  echo ${dir}                                                                  
done

to zip a whole bunch of files by directory

for dir in directory/*
do
  zip -r ${dir##*/} ${dir}
done                                               
查看更多
一纸荒年 Trace。
3楼-- · 2020-01-24 11:10

All answers so far use find, so here's one with just the shell. No need for external tools in your case:

for dir in /tmp/*/     # list directories in the form "/tmp/dirname/"
do
    dir=${dir%*/}      # remove the trailing "/"
    echo ${dir##*/}    # print everything after the final "/"
done
查看更多
爷、活的狠高调
4楼-- · 2020-01-24 11:13

Works with directories which contains spaces

Inspired by Sorpigal

while IFS= read -d $'\0' -r file ; do 
    echo $file; ls $file ; 
done < <(find /path/to/dir/ -mindepth 1 -maxdepth 1 -type d -print0)

Original post (Does not work with spaces)

Inspired by Boldewyn: Example of loop with find command.

for D in $(find /path/to/dir/ -mindepth 1 -maxdepth 1 -type d) ; do
    echo $D ;
done
查看更多
登录 后发表回答