3

This command works fine

find . -name "test"

But i want to do like this in shell script

$FIND = "find . -name "

so that i can use $FIND "test"

but its not working

user3214546
  • 6,523
  • 13
  • 51
  • 98

3 Answers3

4

Consider the statement:

$Find = "find . -name "

There are two things wrong with this:

  1. The shell requires that there be no spaces around the = in an assignment.

  2. $Find is the value of a variable. It is not the variable itself.

Thus, to assign a value to Find, use:

Find="find . -name "

It is not possible to run:

$Find test

This approach is portable but limited. In the long run, it is better to use arrays for this sort of problem.

Lastly, it is best practices not to use all caps for variable names. The system uses all caps for its variables and you don't want to accidentally overwrite one.

Using arrays

One can define an array for this as follows:

Find=(find . -name)

The array can be used as follows:

"${Find[@]}" test

For the simple example that you showed, there is no difference between the array solution and the simpler variable solution. Once the command gets a bit more complicated and requires, say, quotes or escapes, though, an array must be used.

John1024
  • 109,961
  • 14
  • 137
  • 171
3

See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!. Short summary: depending on what you're actually trying to accomplish, use either a function or an array.

For your specific example, I'd use a function:

find_name() {
    find . -name "$1"
}

find_name "test"
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • Or an alias, given the argument's at the end. – paxdiablo Sep 10 '15 at 01:30
  • @paxdiablo That'd work too. I tend to prefer functions over aliases because they work in scripts as well as interactively, and they give more control over arguments -- in this case, I don't think either of those is relevant, so an alias should be fine. – Gordon Davisson Sep 10 '15 at 15:58
1

What about use eval? That seems to be the easiest way if you need to use a variable. It could look like this:

find="find . -name"
eval $find test

But you should be careful with eval.

Anyway alias or function would be better for this, if you don't have any special requirements for a variable. Alias is absolutely the easiest way, function is more flexible (you can put there any logic you need):

# alias
alias find="find . -name"
find test

# function
find() {
    find . -name "$*"
}
find test
Community
  • 1
  • 1
David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
  • OK, great, use an **alias** then. It's designed exactly for what you need. Use of a variable for this purpose is very weird, therefore there is no straightforward way to execute a content in a variable. – David Ferenczy Rogožan Sep 10 '15 at 01:26