Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script grep to grep a string

Tags:

grep

bash

The output is blank fr the below script. What is it missing? I am trying to grep a string

#!/bin/ksh    
file=$abc_def_APP_13.4.5.2    
if grep -q abc_def_APP $file; then
 echo "File Found"
else
 echo "File not Found"
fi
like image 488
Jill448 Avatar asked May 09 '13 18:05

Jill448


2 Answers

In bash, use the <<< redirection from a string (a 'Here string'):

if grep -q abc_def_APP <<< $file

In other shells, you may need to use:

if echo $file | grep -q abc_def_APP

I put my then on the next line; if you want your then on the same line, then add ; then after what I wrote.


Note that this assignment:

file=$abc_def_APP_13.4.5.2

is pretty odd; it takes the value of an environment variable ${abc_def_APP_13} and adds .4.5.2 to the end (it must be an env var since we can see the start of the script). You probably intended to write:

file=abc_def_APP_13.4.5.2

In general, you should enclose references to variables holding file names in double quotes to avoid problems with spaces etc in the file names. It is not critical here, but good practices are good practices:

if grep -q abc_def_APP <<< "$file"
if echo "$file" | grep -q abc_def_APP
like image 105
Jonathan Leffler Avatar answered Nov 10 '22 15:11

Jonathan Leffler


Yuck! Use the shell's string matching

if [[ "$file" == *abc_def_APP* ]]; then ...
like image 20
glenn jackman Avatar answered Nov 10 '22 15:11

glenn jackman