0

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?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
user3407570
  • 125
  • 2
  • 11
  • 3
    http://mywiki.wooledge.org/BashGuide – Etan Reisner Jun 23 '15 at 15:44
  • Also, see the rules in the Help Center. When asking a question about code that misbehaves, you should always include the specific error or misbehavior (no matter how obvious you might expect it to be to someone reading your code), and include only the bare minimum code needed for that error or misbehavior to occur. In this case, reading the BashGuide (and thus getting a basic understanding of the language) is the better place to start. – Charles Duffy Jun 23 '15 at 16:31

2 Answers2

1

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

Community
  • 1
  • 1
Jahid
  • 21,542
  • 10
  • 90
  • 108
  • 2
    `grep -q pattern path` is more efficient than `grep pattern path >/dev/null`, as it allows grep to stop as soon as it finds a match, rather than needing to proceed through the rest of the file generating output that gets thrown away. – Charles Duffy Jun 23 '15 at 16:25
  • 1
    I'd also suggest using `>/dev/null 2>&1` only if that's very explicitly desired -- throwing away errors rather than presenting them to the user hides the causation behind unexpected failures. – Charles Duffy Jun 23 '15 at 16:25
0

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 || {
....
....
}
stolzem
  • 354
  • 1
  • 7
  • 4
    Noooo!!! `cat file | grep` is UUoC: use `grep ... file`. Also, this is quite too much, you can just use `grep -q` for the same purpuse. – fedorqui Jun 23 '15 at 15:58