grep output of command to return 1 or 0 for if then statement
So, I'm new here. Was thrown into the deepend (read: shallow pool) of linux administration of a few centos 6.5 servers in October, and I've been pretty slow on the uptake. Years of Windows administration and desktop support will do that I guess.
So we have qmail on our prod servers that send out messages for our webapps. Postfix failed last night on a prod server, and it occurred to me that it's happened a few times since I've started, and instead of waiting for clients to tell us, I should be more proactive. I came up with/begged/borrowed/stole a quick script to check to see if postscript was running, and if it was, restart it, and contact us. This was to be run from jenkins. Quote:
To get this to work, I thought it would be a good idea to run two scripts. One to check if the mail queue is empty, and if not, send up a flag. The next was to run a few minutes later to check and see if the mail queue was throwing up a fatal error, and if it was, throw up a second flag, which sent out an email from jenkins. Incidentally, if the mailqueue were clogged, this would also trigger an alert. Our mailqueue doesn't get a lot of traffic. First command. Returns then and else statement without issue. Quote:
Quote:
|
It looks you're trying to run a if statement based on whether grep fails or suceeds.
Remember, a successful command will output a error code of 0 If it fails, sometimes 1, or other various codes based on the error. You can view the error code of the previous command with $? So to test if mailq output has the string 'empty' in it: Code:
if [ "$(mailq | grep 'empty' &>/dev/null; echo $?)" == 0 ]; then echo success; else echo failure; fi Code:
if [ "$(mailq | grep 'fatal' &>/dev/null; echo $?)" != 0 ]; then echo 'Mail is up.'; else echo 'Mail queue is not empty. Please check mail server'; fi This is not the only way to do it of course. |
In your second example, replace your single paren.s with doubles. ((<exp>)) is NOT the same as (<exp>).
|
Or we could just let 'if' do the heavy lifting:
Code:
if mailq | grep -q 'fatal' |
Miati, thank you not only for your help, but teaching me something new! Had no idea you could use echo $? for that. PTrenholme, grail, thanks for replying!
|
Quote:
Read the man page of bash (yes - RTM) There is a abundant amount of information that is very useful when writing bash scripts and just using bash in general. Reading over the sections I listed below will save you months of browsing the web for why does n do this. I use most of the below daily (or even by the minute) You can use / to search within man pages & lowercase n to go next in search (N previous) Some things I greatly suggest examining is
If any of it is confusing, feel free to ask for clarification. I also always suggest this as well |
All times are GMT -5. The time now is 03:02 PM. |