How to go to each directory and execute a command?

后端 未结 10 955
無奈伤痛
無奈伤痛 2020-12-02 04:13

How do I write a bash script that goes through each directory inside a parent_directory and executes a command in each directory

相关标签:
10条回答
  • 2020-12-02 04:20

    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"
    
    0 讨论(0)
  • 2020-12-02 04:22
    for dir in PARENT/*
    do
      test -d "$dir" || continue
      # Do something with $dir...
    done
    
    0 讨论(0)
  • 2020-12-02 04:23

    You can do the following, when your current directory is parent_directory:

    for d in [0-9][0-9][0-9]
    do
        ( cd "$d" && your-command-here )
    done
    

    The ( and ) create a subshell, so the current directory isn't changed in the main script.

    0 讨论(0)
  • 2020-12-02 04:23

    This answer posted by Todd helped me.

    find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && pwd" \;
    

    The \( ! -name . \) avoids executing the command in current directory.

    0 讨论(0)
  • 2020-12-02 04:25

    I don't get the point with the formating of the file, since you only want to iterate through folders... Are you looking for something like this?

    cd parent
    find . -type d | while read d; do
       ls $d/
    done
    
    0 讨论(0)
  • 2020-12-02 04:25
    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
    
    0 讨论(0)
提交回复
热议问题