BASH test if file name ends with .dylib

Viewed 292

I'm walking a file tree in order to identify all .DYLIB files.

#!/bin/bash

#script to recursively travel a dir of n levels

function traverse() {
for file in "$1"/*
do
    if [ ! -d "${file}" ] ; then
        echo "${file} is a file"
    else
        echo "entering recursion with: ${file}"
        traverse "${file}"
    fi
done
}

function main() {
    traverse "$1"
}

main "$1"

I want to test if the filename ends with .DYLIB before printing "... is a file". I think I may need to add to the condition "if [ ! -d "${file}" ] ; then", but I'm not sure. Is there a way to do this in bash?

2 Answers

No need to write your own recursive function. You can recursively find all *.dylib files using a ** glob:

shopt -s globstar
ls "$1"/**/*.dylib

Or use find:

find "$1" -name '*.dylib'

To use these results I recommend looping over them directly. It avoids using up memory with a temporary array.

shopt -s globstar

for file in "$1"/**/*.dylib; do
    echo "$file"
done

or

while IFS= read -rd '' file; do 
    echo "$file"
done < <(find "$1" -name '*.dylib')

Is there a way I can store everything in a string array so that I can perform an operation on those .dylib files?

But if you do indeed want an array, you can write:

shopt -s globstar
files=("$1"/**/*.dylib)

or

readarray -td '' files < <(find "$1" -name '*.dylib')

Then to loop over the array you'd write:

for file in "${files[@]}"; do
    echo "$file"
done

Don't add to the condition in if [ ! -d "$file" ], because then the else block will try to recurse into files that don't have the suffix. But recursion should only be for directories.

You should add a nested condition for this. You can use bash's [[ ]] condition operator to have = perform wildcard matching.

if [ ! -d "${file}" ] ; then
    if [[ "$file" = *.DYLIB ]]; then 
        echo "${file} is a file"
    fi
else
    echo "entering recursion with: ${file}"
    traverse "${file}"
fi

Or you could invert the sense of the directory test:

if [ -d "$file" ]; then
    echo "entering recursion with: ${file}"
    traverse "${file}"
elif [ "$file" = *.DYLIB ]; then
    echo "$file is a file"
fi
Related