Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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 .

like image 871
EMC Avatar asked Nov 30 '10 15:11

EMC


People also ask

How do you pass variables in bash?

Passing Arguments as an Array to Variable:Add a default variable “$@” which will store the arguments entered by the user as an array. These arguments will be parsed to variable “array”. The last line will display all the arguments of the variable “array” sorted by the index number. Execute the “./” shell script.

Can you assign variables in bash?

A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.

How do you pass a variable to a function in shell script?

Syntax for defining functions: To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.


1 Answers

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.

like image 69
Darron Avatar answered Nov 15 '22 09:11

Darron