Search code examples
bashfunctionfindexec

how to use a bash function defined in your .bashrc with find -exec


my .bashrc has the following function

function myfile {
 file $1
}
export -f myfile

it works fine when i call it directly

rajesh@rajesh-desktop:~$ myfile out.ogv 
out.ogv: Ogg data, Skeleton v3.0

it does not work when i try to invoke it through exec

rajesh@rajesh-desktop:~$ find ./ -name *.ogv -exec myfile {} \;
find: `myfile': No such file or directory

is there a way to call bash script functions with exec?

Any help is greatly appreciated.

Update:

Thanks for the response Jim.

But that's exactly what I wanted to avoid in the first place, since I have lot of utility functions defined in my bash scripts, I wanted to use them with other useful commands like find -exec.

I totally see your point though, find can run executables, it has no idea that the argument passed is function defined in a script.

I will get the same error when I try to exec is on bash prompt.

$ exec myfile out.ogv

I was hoping that there may be some neat trick that exec could be given some hypothetical command like "bash -myscriptname -myfunctionname".

I guess I should try to find some way to create a bash script on the fly and run it with exec.


Solution

  • You can get bash to run a function by putting the command into bash's StdIn:

    bash$ find ./ -name *.ogv -exec echo myfile {} \; | bash
    

    The command above will work for your example but you need to take note of the fact that all of the 'myfile...' commands are generated at once and sent to a single bash process.