Have the find Command Invoke A Custom Shell Function

Published: 2022-12-24 00:43:11 +0000
Categories: BASH, Misc,




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


# Define your function
function doSomething(){
    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 {}' \;


shell, find, bash, exec, sh,

Latest Posts

Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter github.com/bentasker