Comment by 1718627440

1 month ago

On my computer

    touch "$(echo -en 'a\nb')"
    find . -type f -name '*.mp3' -exec bash -c "echo '{}'; ls '{}'" ';'

works just fine, but maybe it doesn't work everywhere.

If you don't like how the multiple commands look like, you can always write it like this:

    find . -type f -name '*.mp3' -exec bash -c "
        echo '{}'
        ls '{}'
    " ';'

Yep, you can chain multiple commands with find's "-exec", but I'm not a fan of it myself. I suspect setting variables in the current process is trickier though.

(Very minor nitpick, it should be 'a\nb.mp3' to be included, but that does work fine)

Incidentally, ShellCheck isn't happy with that although I don't follow their reasoning:

  find . -type f -name '*.mp3' -exec bash -c "
                                           ^-- SC2156 (warning): Injecting filenames is fragile and insecure. Use parameters.

https://www.shellcheck.net/wiki/SC2156

  • > although I don't follow their reasoning

    I think it is sound. Imagine what happens when the filename contains:

        ' && shutdown now && '.mp3

    • Of course that makes sense now.

      Anyhow here's an example of how I would use the while loop and process substitution in a BASH script:

        declare -i file_count=0
        while IFS= LC_ALL=C read -r -d '' file; do
          file_count+=1
          printf "file: %s\n"  "${file}"
        done < <(find . -type f -name '*.mp3' -print0)
        printf "Processed %d files\n" "${file_count}"
      

      I think that'd be tricky to do using just a find/-exec command.

      2 replies →