How to go to each directory and execute a command?

后端 未结 10 1034
無奈伤痛
無奈伤痛 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"
    

提交回复
热议问题