我正在Linux上编写bash脚本,需要遍历给定目录中的所有子目录名。如何遍历这些目录(并跳过常规文件)?

例如: 指定目录为/tmp/ 目录包括:/tmp/A、/tmp/B、/tmp/C

我想找回A B C。


当前回答

如果你想在一个for循环中执行多个命令,你可以用mapfile (bash >= 4)将find的结果保存为一个变量,然后用${dirlist[@]}遍历数组。它还适用于包含空格的目录。

find命令基于Boldewyn的回答。关于find命令的更多信息可以在这里找到。

IFS=""
mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
    echo ">${dir}<"
    # more commands can go here ...
done

其他回答

find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"

到目前为止,所有答案都使用find,这里有一个只有外壳的答案。在您的情况下不需要外部工具:

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

简而言之,将find的结果放入一个数组并迭代该数组并执行您想要的操作。不是最快的,而是更有条理的思考。

#!/bin/bash

cd /tmp

declare -a results=(`find -type d`)

#Iterate the results

for path in ${results[@]}
do
    echo "Your path is $path"
    #Do something with the path..

    if [[ $path =~ "/A" ]]; then
        echo $path | awk -F / '{print $NF}'
        #prints A

    elif [[ $path =~ "/B" ]]; then
        echo $path | awk -F / '{print $NF}'
        #Prints B

    elif [[ $path =~ "/C" ]]; then
        echo $path | awk -F / '{print $NF}'
        #Prints C
    fi
done

这可以简化为查找-type d | grep "/A" | awk -F / '{print $NF}'打印A

find -type d | grep "/B" | awk -F / '{print $NF}'打印B find -type d | grep "/C" | awk -F / '{print $NF}'打印C

可以构建的最小bash循环(基于ghostdog74答案)

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

按目录压缩一大堆文件

for dir in directory/*
do
  zip -r ${dir##*/} ${dir}
done                                               
cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'

简单解释一下:

find finds files (quite obviously) . is the current directory, which after the cd is /tmp (IMHO this is more flexible than having /tmp directly in the find command. You have only one place, the cd, to change, if you want more actions to take place in this folder) -maxdepth 1 and -mindepth 1 make sure that find only looks in the current directory and doesn't include . itself in the result -type d looks only for directories -printf '%f\n prints only the found folder's name (plus a newline) for each hit.

就是这样!