Issue
I have a find-grep command that I frequently use. Over the past two years, I have been curating it and adding more stuff to it to make it more useful. Originally I had it in a text file on my Desktop. I used to copy paste the command when ever I needed it. Some time last year, I got the idea to add it to my ~/.bashrc file directly. This is the code I came up with:
findg() {
if [ "$#" -lt 2 ]; then
echo "args: (1) File pattern (2) Args to grep"
return
fi
pattern=$1
file_pattern=$(basename pattern)
directory_path=$(dirname pattern)
# Remove the first argument from the list, so you will only be left with GREP arguments.
shift
find $directory_path -name "$file_pattern" -exec grep -Hn --color=always -A 5 -B 5 --group-separator=\n=======================\n -E $* {} \;| less -R
}
I tried calling the function in various ways, like:
findg "$PWD/source_dir/'*.py'" "'special_function\(self'"
findg $PWD/source_dir/"'*.py'" "'special_function\(self'"
findg $PWD/source_dir/"*.py" "'special_function\(self'"
findg $PWD/source_dir/"\*.py" "'special_function\(self'"
In almost all the situation it seems to expand the wild card first then it passes the expanded output to my function call. How can I pass a string to my bash function.
Sorry, if I seem clueless about what I am trying to do, I am a newbie to Bash scripting.
Solution
As long as you are correctly quoting the pattern when calling findg
, you don't need additional quotes in the pattern.
findg "$PWD/source_dir/*.py" "special_function\(self"
The quoting in your function does need fixing with regard to the regular expressions, though.
findg() {
if [ "$#" -lt 2 ]; then
echo "args: (1) File pattern (2) Args to grep"
return
fi
pattern=$1
file_pattern=$(basename "$pattern")
directory_path=$(dirname "$pattern")
# Remove the first argument from the list, so you will only be left with GREP arguments.
shift
find "$directory_path" -name "$file_pattern" \
-exec grep -Hn --color=always -A 5 -B 5 \
--group-separator="\n=======================\n" \
-E "$@" {} \; | less -R
}
Answered By - chepner