How to loop over files and directories using bash script? – Code Example

To loop over files and directories, we will provide you bash script code. This code can fetch all files and folder, selected extension only, only files, only folders, and nested folders.

Code Example –

1. All files in current directory –

#!/bin/bash

for file in *; do
    printf '%s\n' "$file"
done

2. All JPEG images in Pictures directory –

#!/bin/bash

for file in ~/Pictures/*.jpeg; do
    printf '%s\n' "$file"
done

3. All directories on Desktop –

#!/bin/bash

for dir in ~/Desktop/*/; do
    printf '%s\n' "$dir"
done

4. Only these files – /Dir1/Dir2/File1, /Dir1/Dir2/File2, /Dir1/Dir2/Dir3/File3

#!/bin/bash

for file in /Dir1/Dir2/{File1,File2,Dir3/File3}; do
    printf '%s\n' "$file"
done

5. All files inside all nested directories –

#!/bin/bash

shopt -s globstar
for file in ~/Pictures/**/*; do
    printf '%s\n' "$file"
done
shopt -u globstar

Inspired from Dylan Araps