Find Files in Directories in Bash
2 min read

Finding Files in Bash

There are two ways I mostly use to find different files in bash. One of the probably better than the other. Both ways saves all the file paths to an array which we can loop through.

For this example, I am going to look for all .yml in a specified directory.

The simplest way to do it would be this command:

FILES=./directory/*/*.yml

This is good if all your files are in the same directory, in this case in ./directory/<any folder>/<file>.yml. However, this is quite stale and does not allow you to find the files in a more dynamic matter. That’s why we probably should use the find command.

FILES=$(find ./directory -type f -name "*.yml")

This command is much more flexiable, as it looks for all files within all directories in the specifed path (./directory in this case.). the type command specifies that we are looking for a file, and we use the name flag to specify the name.We save the output to the FILES variable.

Once we have our files, we can loop through them as normal:

for file in $FILES; do
    # do some logic
done