Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I often run find in my code projects when I make a change somewhere and I have to find where it impacts other pieces of code, so I thought about writing a very small script to make this easier, call it blah.sh:

#!/bin/bash -eu

if [ $# -ne 3 ]; then
    echo "Three inputs required"
else
    find $1 -name $2 -exec grep -iHn $3 {} \;
fi

The problem is, I get an error when the third argument (the text I'm looking for) contains a space. For example, blah . '*.php' 'foo bar' returns grep: bar: No such file or directory for each file grep tried to explore. I'm sure it's a silly mistake, I'm not really hands on with bash..

share|improve this question

1 Answer

up vote 6 down vote accepted

have you tried like this:

find "$1" -name "$2" -exec grep -iHne "$3" {} +

Without the quotes, bash performs word splitting and filename generation on the variables, so they wind up getting passed as multiple arguments.

share|improve this answer
 
You forgot a couple. –  Ignacio Vazquez-Abrams Aug 22 at 15:29
 
Hmm, I was sure I tried that and got another error when I passed a third argument with double quotes, but it's working right now with the query I had in mind.. –  Sh3ljohn Aug 22 at 15:30
2  
I added in quoting the other two parameters and also a brief explanation of why. Please feel free to revert if you don't agree. –  derobert Aug 22 at 15:31
 
Alright, well, it seems to work now, I must have done something wrong when I tried before... Thanks, that was easy :) –  Sh3ljohn Aug 22 at 15:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.