I am trying to write a script that will apply a bash function for each file in a directory recursively. For example if the directory tests had all my files and sub-directories in it, the script
find tests -type f -print0 | xargs -0 echo
Works perfectly. Now I want to be able to apply a bash function rather than just echo, so I came up with something like this:
function fun() {
echo $1
}
export -f fun
find tests -type f -print0 | xargs -0 bash -c 'fun "$@"'
However this only outputs a single file in tests, where before it output all the files. I would expect these two to run the same no?
bash -c, you get a non-interactive shell, which doesn't look at.bashrc. Secondly, does your function look at multiple arguments? Thirdly, you should saybash -c 'fun "$@"' sh, because the first word after the command string afterbash -cis assigned to$0, and therefore isn't included in"$@". … … … … … … … … … … … … … … … … OK, ignore the first point; I hadn't noticed that you had exported the function.echo)xargsexecutes the command with all the files at once (or, at least, as many as can be passed on one command line — this is in the thousands) and not once per command. Since your function prints only$1(and not all the arguments), you get only one.