Skip to content

Instantly share code, notes, and snippets.

@jwliechty
Last active August 11, 2021 20:29
Show Gist options
  • Save jwliechty/17b476005bb8b665792b to your computer and use it in GitHub Desktop.
Save jwliechty/17b476005bb8b665792b to your computer and use it in GitHub Desktop.
Example of how to use find exec calling a function.
#/bin/bash
export MY_EXPORTED_VAR="Boo Yeah!"
MY_NON_EXPORTED_VAR="You won't see this one!"
# This script was inspired by the answer to the question in
# http://unix.stackexchange.com/questions/50692/executing-user-defined-function-in-a-find-exec-call
runFindCommand(){
# 'myFunct "$@"' will call the function with the arguments passed into the shell
# the reason for 'bash {} \;' is that those are positional parameters where
# $0 is 'bash' (typically the name of the script)
# $1 is the filepath
find . -exec bash -c 'myFunction "$@"' bash {} \;
}
myFunction(){
local file="$1"
echo "I have file ${file}"
echo "I can also access exported global variables"
echo " such as MY_EXPORTED_VAR=${MY_EXPORTED_VAR}"
echo " but not MY_NON_EXPORTED_VAR=${MY_NON_EXPORTED_VAR}"
echo "I can access exported functions - $(anotherExportedFunction)"
echo "But not non exported functions - $(nonExportedFunction)"
}
anotherExportedFunction(){
echo "I can access exported functions"
}
nonExportedFunction(){
echo "You will not be able to see this method"
}
export -f myFunction
export -f anotherExportedFunction
runFindCommand
@jwliechty
Copy link
Author

jwliechty commented Aug 11, 2021

@princefishthrower I have not found an in-memory way of communicating values from subshells. Exported global variables travel in one direction only -- parents to child process. The only way I have found to communicate data from a child process to a parent process is to write values to a file. The parent can then read that file to get an answer from a child process.

So in your case, have your myFunction increment a count in a file. Your calling parent can then read that count once the child functions finish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment