如何使用find -exec在.bashrc中定义的bash函数

sha*_*esh 17 bash function exec find

我的.bashrc具有以下功能

function myfile {
 file $1
}
export -f myfile
Run Code Online (Sandbox Code Playgroud)

当我直接调用它时它工作正常

rajesh@rajesh-desktop:~$ myfile out.ogv 
out.ogv: Ogg data, Skeleton v3.0
Run Code Online (Sandbox Code Playgroud)

当我尝试通过exec调用它时,它不起作用

rajesh@rajesh-desktop:~$ find ./ -name *.ogv -exec myfile {} \;
find: `myfile': No such file or directory
Run Code Online (Sandbox Code Playgroud)

有没有办法用exec调用bash脚本函数?

任何帮助是极大的赞赏.

更新:

谢谢Jim的回应.

但这正是我想要首先避免的,因为我在bash脚本中定义了很多实用函数,我想将它们与find -exec等其他有用的命令一起使用.

我完全看到你的观点,发现可以运行可执行文件,它不知道传递的参数是在脚本中定义的函数.

当我尝试exec处于bash提示符时,我将得到相同的错误.

$ exec myfile out.ogv
Run Code Online (Sandbox Code Playgroud)

我希望可能有一些巧妙的技巧,exec可以给出一些假设的命令,如"bash -myscriptname -myfunctionname".

我想我应该尝试找到一些方法来动态创建一个bash脚本并使用exec运行它.

小智 7

find ./ -name *.ogv -exec bash -c 'myfile {}' \;
Run Code Online (Sandbox Code Playgroud)

  • 您应该引用文件名:`bash -c'myfile"{}"'`. (2认同)

Pet*_*lák 7

我设法以更优雅的方式运行它:

function myfile { ... }
export -f myfile
find -name out.ogv -exec bash -c '"$@"' myfile myfile '{}' \;
Run Code Online (Sandbox Code Playgroud)

注意myfile两次给出.第一个是$0脚本的参数(在这种情况下,它基本上可以是任何东西).第二个是要运行的函数的名称.


msw*_*msw 6

$ cat functions.bash
#!/bin/bash

function myecho { echo "$@"; }
function myfile { file "$@"; }
function mycat { cat "$@"; }

myname=`basename $0`
eval ${myname} "$@"
$ ln functions.bash mycat
$ ./mycat /etc/motd
Linux tallguy 2.6.32-22-core2 ...
$ ln functions.bash myfile
$ myfile myfile
myfile: Bourne-Again shell script text executable
$ ln functions.bash myecho
$ myecho does this do what you want\?
does this do what you want?
$ 
Run Code Online (Sandbox Code Playgroud)

当然,这些功能可能比我的例子更复杂.


too*_*php 5

通过将命令放入bash的StdIn中,可以使bash运行函数:

bash$ find ./ -name *.ogv -exec echo myfile {} \; | bash
Run Code Online (Sandbox Code Playgroud)

上面的命令将适用于您的示例,但是您需要注意以下事实:所有' myfile...'命令都立即生成并发送到单个bash进程。