简体   繁体   English

如何在 find 和 bash -c 中传递变量?

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

I have issues with passing variable to %exe part of the code.我在将变量传递给代码的 %exe 部分时遇到问题。

Here is my working code that I use inside bash script:这是我在 bash 脚本中使用的工作代码:

## 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 .但它生成的文件名如: 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 :使用envbash设置环境变量:

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.我添加了一些引用以防止文件名中出现空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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