Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute bash function from find command

Tags:

bash

xargs

I have defined a function in bash, which checks if two files exists, compare if they are equal and delete one of them.

function remodup {
    F=$1
    G=${F/.mod/}
    if [ -f "$F" ] && [ -f "$G" ]
    then
        cmp --silent "$F" "$G" && rm "$F" || echo "$G was modified"
    fi
}

Then I want to call this function from a find command:

find $DIR -name "*.mod" -type f -exec remodup {} \;

I have also tried | xargs syntax. Both find and xargs tell that ``remodup` does not exist.

I can move the function into a separate bash script and call the script, but I don't want to copy that function into a path directory (yet), so I would either need to call the function script with an absolute path or allways call the calling script from the same location.

(I probably can use fdupes for this particular task, but I would like to find a way to either

  1. call a function from find command;
  2. call one script from a relative path of another script; or
  3. Use a ${F/.mod/} syntax (or other bash variable manipulation) for files found with a find command.)
like image 247
Carlos Eugenio Thompson Pinzón Avatar asked Jun 16 '15 22:06

Carlos Eugenio Thompson Pinzón


People also ask

How do I execute a function in bash?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

What action can the find command use to execute commands?

find will execute grep and will substitute {} with the filename(s) found. The difference between ; and + is that with ; a single grep command for each file is executed whereas with + as many files as possible are given as parameters to grep at once.

Is find a bash command?

The Bash find command in Linux offers many ways to search for files and directories. In this tutorial, you'll learn how a file's last-time access, permissions, and more can help find files and directories with the Bash find command. Let's get started!


1 Answers

You need to export the function first using:

export -f remodup

then use it as:

find $DIR -name "*.mod" -type f -exec bash -c 'remodup "$1"' - {} \;
like image 81
anubhava Avatar answered Sep 23 '22 02:09

anubhava