How do I pass variable inside find and bash -c?

Try:

targz() {
  find $1 -type f -name "*.$2" -exec \
    bash -c 'old=$(basename {}); new=${old/'"$2"'/tar\.gz}; \
      tar -zcvf $new $old; ' \;
}

The trick is to get out of the single quote, so that variable expansion will be performed.


Use env to set an environment variable for bash:

targz() {
  find "$1" -type f -name "*.$2" -exec \
    env ext="$2" bash -c 'old=$(basename "{}"); new=${old/%$ext/tar\.gz}; \
      tar -zcvf "$new" "$old"; ' \;
}

I added some quoting to protect against spaces in filenames.

Tags:

Bash