user3407570
user3407570

Reputation: 125

Executing code in bash only if a string is not found in a file

I'm trying to execute a block of code only if the string SVN_BRANCH is not found in /etc/profile. My current code looks like the following:

a = cat /etc/profile
    b = `$a | grep 'SVN_BRANCH'`

    not_if "$b"
{
....
... 
...
}

This fails as given. How should it be done?

Upvotes: 0

Views: 63

Answers (2)

Jahid
Jahid

Reputation: 22428

grep can take file as an argument, you don't need to cat the file and then pass the content to grep with pipe, that's totally unnecessary.

This is an example of if else block with grep:

if grep -q "pattern" filepath;then
echo "do something"
else
echo "do something else"
fi

Note:

-q option is for quite operation. It will hide the output of grep command (error will be printed).

If you want it to not print any errors too then use this:

if grep -sq "pattern" filepath;then

Or this:

if grep "pattern" filepath >/dev/null 2>&1;then

>/dev/null is to redirect the output to /dev/null

2>&1 redirects both stderr and stdout

Upvotes: 1

stolzem
stolzem

Reputation: 364

you can use the exit code of the grep command to determine whether to execute your code block like this

cat /etc/profile | grep SVN_BRANCH 2>&1 >/dev/null || {
....
....
}

Upvotes: 0

Related Questions