find -exec a shell function in Linux?

2020-01-27 09:52发布

Is there a way to get find to execute a function I define in the shell? For example:

dosomething () {
  echo "doing something with $1"
}
find . -exec dosomething {} \;

The result of that is:

find: dosomething: No such file or directory

Is there a way to get find's -exec to see dosomething?

13条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-27 09:57

Have the script call itself, passing each item found as an argument:

#!/bin/bash

if [ ! $1 == "" ] ; then
   echo "doing something with $1"
   exit 0
fi

find . -exec $0 {} \;

exit 0

When you run the script by itself, it finds what you are looking for and calls itself passing each find result as the argument. When the script is run with an argument, it executes the commands on the argument and then exits.

查看更多
乱世女痞
3楼-- · 2020-01-27 09:57

It is not possible to executable a function that way.

To overcome this you can place your function in a shell script and call that from find

# dosomething.sh
dosomething () {
  echo "doing something with $1"
}
dosomething $1

Now use it in find as:

find . -exec dosomething.sh {} \;
查看更多
▲ chillily
4楼-- · 2020-01-27 10:00

I would avoid using -exec altogether. Why not use xargs?

find . -name <script/command you're searching for> | xargs bash -c
查看更多
三岁会撩人
5楼-- · 2020-01-27 10:05
find . | while read file; do dosomething "$file"; done
查看更多
聊天终结者
6楼-- · 2020-01-27 10:06

Put the function in a separate file and get find to execute that.

Shell functions are internal to the shell they're defined in; find will never be able to see them.

查看更多
何必那么认真
7楼-- · 2020-01-27 10:08

Since only the shell knows how to run shell functions, you have to run a shell to run a function. You also need to mark your function for export with export -f, otherwise the subshell won't inherit them:

export -f dosomething
find . -exec bash -c 'dosomething "$0"' {} \;
查看更多
登录 后发表回答