Reputation: 338
Here is my problem. To get a list of directory where the file GC.xml is:
EXBRANDS=
find /var/www/html/ -maxdepth 3 -name "GC.xml" -type f | awk -F '/' '{print $5}';
#echo $EXBRANDS
#dir1 dir2 dir3 (it appears exactly like this)
#read var
Enter "dir" for example
That's where I'm having trouble to identify the exact pattern I typed to compare it against my directory list.
echo $EXBRANDS | grep "[ $var]\|[$var ]\|[ $var]"
if [[ $? -eq 0 ]] ; then ..... else ..... fi;
I think there is a problem with my grep command as if I pass the value "dir" to $var my grep command actually finds the directory and returns $?=0
My wish is to get $?=0 only if it finds exactly the pattern $var in my grep command...
What are the best grep (egrep) options here? Or is my method completely stupid?
Upvotes: 1
Views: 1373
Reputation: 19224
Try using word boundaries:
if [ ! -z "$var" ] ;
then echo $EXBRANDS | grep -e "\b$var\b";
if [[ $? -eq 0 ]] ;
then echo "Y";
else echo "N";
fi;
else echo "input dir must be not null";
fi;
EDIT: add null check
Upvotes: 1
Reputation: 16768
Your EXBRANDS
contains many lines, and you loose these lines with echo.
I would do that the other way:
read var
find /var/www/html/ -maxdepth 3 -name "GC.xml" -type f | awk -F '/' '{print $5}' | grep "^$var\$"
if [[ $? -eq 0 ]] ; then ... else ... fi;
Be sure that the grep match an exact line with the "^$var\$"
construct.
Edit: you could also printf "$EXBRANDS" | grep "^$var\$"
instead of echo, it might solve your problem.
Upvotes: 2