Last active
August 11, 2021 20:29
-
-
Save jwliechty/17b476005bb8b665792b to your computer and use it in GitHub Desktop.
Example of how to use find exec calling a function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#/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 |
@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
Is it possible to modify the exported vars? For example, I want to keep a count of files I visit within
myFunction
.