开发者

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

开发者 https://www.devze.com 2023-01-27 09:51 出处:网络
I have issues with passing variable to %exe part of the code. Here is my working code that I use inside bash scri开发者_Go百科pt:

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

Here is my working code that I use inside bash scri开发者_Go百科pt:

## 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消