Reputation: 33
I have a question regarding the usage of functions in a command in bash. getRegex
is my function, it is defined at the end of the the file. The command that I want to use is the following:
COUNT=`grep -rnE 'getRegex' $HOME/new`
Now I tried a lot of different variants but I cannot make it work, even if I split it in 2. The method works correctly if I call it the following way: getRegex
. Any idea what I am missing? TIA
Upvotes: 3
Views: 4304
Reputation: 21972
The key words to answer are "bash command substitution", which you could find in man bash
or google.
By the way, double quotes are really important here.
#!/bin/bash
function my_func () {
echo "no"
}
string="no you don't
no you don't
no you don't
no you don't
no you don't"
COUNT="$( echo "${string}" | grep "$( my_func )" -c )"
echo "${COUNT}"
And
$> ./ok.sh
5
Upvotes: 4
Reputation: 10786
If you're trying to call a bash command within another bash command, the inner command (here getRegex) needs to be enclosed in backticks ``
or else it will be interpreted as text. Since you here would have backticks inside backticks, you'll need to escape the inner ones. Try this:
COUNT=`grep -rnE '\`getRegex\`' $HOME/new`
But, through the wonders of POSIX, we can use a different syntax. Anywhere you use backticks, you can also use $()
. So to avoid backslash emesis, you could write:
COUNT=$(grep -rnE '$(getRegex)' $HOME/new)
Upvotes: 0