1

In one of my Bash scripts I have such code repeated twice:

    find "$source_dir" -type f \
            -iname "*.arw" \
            -or -iname "*.cr2" \
            -or -iname "*.crw" \
            -or -iname "*.jpeg" \
            -or -iname "*.jpg" \
            -or -iname "*.nef" \
            -or -iname "*.nrw" \
            -or -iname "*.orf" \
            -or -iname "*.pef" \
            -or -iname "*.png" \
            -or -iname "*.ptx" \
            -or -iname "*.raf" \
            -or -iname "*.raw" \
            -or -iname "*.rw2" \
            -or -iname "*.sr2" \
            -or -iname "*.srf" \
            -or -iname "*.srw" \
            -or -iname "*.tif" \
            -or -iname "*.tiff" \
            -or -iname "*.x3f" | (

     counter=0

     while read image_file; do
            (...)

There are two such find commands both performed on different directories, but with exactly the same parameters. Results of each finds are processed in a different ways. I am convinced that it is possible to avoid code duplication here. Is there a way to wrap this find command into a function that stores find results in some data structure? Such data structure must be passed to the subshell that iterates over its items. How can I achieve this?

  • 1
    If your version of `find` supports it, you can greatly reduce the length of the command: `find "$source_dir" -type f -iregex "*.(cr2|crw|jpeg|...|x3f)$"`. – chepner Jul 21 '14 at 14:45
  • 1
    Also, technically the `-type f` predicate only applies to `arw` files; you probably want something like `find ... -type f \( -iname "*.arw" -o -iname "*.cr2 -o ... \)`. – chepner Jul 21 '14 at 14:47

1 Answers1

2

Wrap the find command as a function

function myfind() {
   find ....
}

and then use it like it is a new command

myfind | while read image_file; do ....
Soren
  • 14,402
  • 4
  • 41
  • 67
  • Also, if you need to pass parameters to the newly created function then that is easy as well -- have a look at this http://stackoverflow.com/questions/6212219/passing-parameters-to-a-bash-function – Soren Jul 20 '14 at 22:18