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.
精彩评论