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
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
Consider the statement:
$Find = "find . -name "
There are two things wrong with this:
The shell requires that there be no spaces around the =
in an assignment.
$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.
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.
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"
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