Have the find Command Invoke A Custom Shell Function (BASH)

The find command accepts and -exec argument, allowing you to pass matching files into an arbitrary command.

It's pretty useful, but sometimes you want to be able to have it invoke a custom function, which it can't do without a little bit of tweaking

This snippet details how to have find invoke a custom shell function against each matching result, the example uses BASH but the same should be possible with ZSH, DASH, ASH, KSH etc

Details

  • Language: BASH

Snippet

# Define your function
function doSomething(){
    file=${1#"./"}    
    do_something_to $file
}

# Export the function
# so that it's available to find
export -f doSomething

# find will need a shell to execute the function
# here we've used bash, but invoke whichever shell is needed
# for your function
find ./ -type f -mtime +14 -exec bash -c 'doSomething {}' \;