我如何编写一个bash脚本,遍历parent_directory内的每个目录,并在每个目录中执行命令。

目录结构如下:

Parent_directory(名称可以是任何东西-不遵循模式) 001(目录名称遵循此模式) 0001.txt(文件名遵循此模式) 0002.三种 0003.三种 002 0001.三种 0002.三种 0003.三种 0004.三种 003 0001.三种 目录数量未知。


当前回答

我不明白文件的格式,因为你只想遍历文件夹…你在找这样的东西吗?

cd parent
find . -type d | while read d; do
   ls $d/
done

其他回答

for p in [0-9][0-9][0-9];do
    (
        cd $p
        for f in [0-9][0-9][0-9][0-9]*.txt;do
            ls $f; # Your operands
        done
    )
done

我不明白文件的格式,因为你只想遍历文件夹…你在找这样的东西吗?

cd parent
find . -type d | while read d; do
   ls $d/
done

你可以使用

find .

递归搜索当前目录下的所有文件/dirs

然后您可以像这样通过xargs命令输出

find . | xargs 'command here'

While one liners are good for quick and dirty usage, I prefer below more verbose version for writing scripts. This is the template I use which takes care of many edge cases and allows you to write more complex code to execute on a folder. You can write your bash code in the function dir_command. Below, dir_coomand implements tagging each repository in git as an example. Rest of the script calls dir_command for each folder in directory. The example of iterating through only given set of folder is also include.

#!/bin/bash

#Use set -x if you want to echo each command while getting executed
#set -x

#Save current directory so we can restore it later
cur=$PWD
#Save command line arguments so functions can access it
args=("$@")

#Put your code in this function
#To access command line arguments use syntax ${args[1]} etc
function dir_command {
    #This example command implements doing git status for folder
    cd $1
    echo "$(tput setaf 2)$1$(tput sgr 0)"
    git tag -a ${args[0]} -m "${args[1]}"
    git push --tags
    cd ..
}

#This loop will go to each immediate child and execute dir_command
find . -maxdepth 1 -type d \( ! -name . \) | while read dir; do
   dir_command "$dir/"
done

#This example loop only loops through give set of folders    
declare -a dirs=("dir1" "dir2" "dir3")
for dir in "${dirs[@]}"; do
    dir_command "$dir/"
done

#Restore the folder
cd "$cur"

您可以通过管道,然后使用xargs来实现这一点。问题是您需要使用-I标志,它将用每个xargs传递的子字符串替换bash命令中的子字符串。

ls -d */ | xargs -I {} bash -c "cd '{}' && pwd"

您可能希望将pwd替换为您想在每个目录中执行的任何命令。