'find -exec' a shell function in Linux
Is there a way to get find
to execute a function I define in the shell?
For example:
dosomething () {
echo "Doing something with $1"
}
find . -exec dosomething {} \;
The result of that is:
find: dosomething: No such file or directory
Is there a way to get find
's -exec
to see dosomething
?
Solution 1:
Since only the shell knows how to run shell functions, you have to run a shell to run a function. You also need to mark your function for export with export -f
, otherwise the subshell won't inherit them:
export -f dosomething
find . -exec bash -c 'dosomething "$0"' {} \;
Solution 2:
find . | while read file; do dosomething "$file"; done
Solution 3:
Jac's answer is great, but it has a couple of pitfalls that are easily overcome:
find . -print0 | while IFS= read -r -d '' file; do dosomething "$file"; done
This uses null as a delimiter instead of a linefeed, so filenames with line feeds will work. It also uses the -r
flag which disables backslash escaping, and without it backslashes in filenames won't work. It also clears IFS
so that potential trailing white spaces in names are not discarded.