Say, I call grep "blabla" $file
in my shell. How could I know whether grep found "blabla" in $file?
I try ret='grep "blabla" $file'
, will this work by viewing the value of ret
? If yes, is ret
integer value or string value or something else?
If you do exactly
ret='grep "blabla" $file'
then ret
will contain the string "grep "blabla" $file".
If you do (what you meant)
ret=`grep "blabla" $file`
then ret
will contain whatever output grep
spit out (the lines that matched "blabla" in $file
).
If you just want to know whether grep
found any lines that matched "blabla" in $file
then you want to check the return code of grep -q blabla "$file"
(note that you don't need to quote literal strings when they don't contain special characters and that you should quote variable references).
The variable $?
contains the return code of the most recently executed command. So
grep -q blabla "$file"
echo "grep returned: $?"
will echo the return code from grep
which will be 0
if any lines were output.
The simplest way to test that and do something about it is, however, not to use $?
at all but instead to just embed the grep
call in an if
statement like this
if grep -q blabla "$file"; then
echo grep found something
else
echo grep found nothing
fi
When you run the command
grep blabla "$file"
Status is saved in the variable $?
. 0 is good, greater than 0 is bad. So you could do
grep -q blabla "$file"
if [ $? = 0 ]
then
echo found
fi
Or save to a variable
grep -q blabla "$file"
ret=$?
if [ $ret = 0 ]
then
echo found
fi
Or just use if
with grep
directly
if grep -q blabla "$file"
then
echo found
fi
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.