简体   繁体   中英

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

I have issues with passing variable to %exe part of the code.

Here is my working code that I use inside bash script:

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

## Function Call
## targz [directory] [extension]
targz . 'exe';

and yes I've tried using it some thing like this:

new=${old/%$2/tar\.gz};

but it generates filenames like: file.exetar.gz .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM