Van de Graff Van de Graff - 1 year ago 62
Bash Question

How to go to each directory and execute a command?

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

The directory structure is as follows:

parent_directory (name could be anything - doesnt follow a pattern)

  • 001 (directory names follow this pattern)

    • 0001.txt (filenames follow this pattern)

    • 0002.txt

    • 0003.txt

  • 002

    • 0001.txt

    • 0002.txt

    • 0003.txt

    • 0004.txt

  • 003

    • 0001.txt

the number of directories is unknown.

Answer Source

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download