-1

I am running bash 5.0.007-1 and net-snmp 5.8-2 on an up to date arch linux.

This line collects the status of a device:

snmpstatus -c public -v1 192.168.1.240

When the device is not powered on, ie the above ip address does not exist on the network, the above command returns the below output to the terminal:

Timeout: No Response from 192.168.1.240

How do I stop this timeout output line displaying in the terminal and capture it to a variable instead. Also if the device is switched on and the ip address exists normal output should be displayed on the terminal as well as passing output to the same variable.

I will parse the variable once I have it and decide what to do depending on its contents.

(I have done a fair bit of reading including man snmpcmd, man smnpwalk and on re-direction but the solution is evading me).

| improve this question | | | | |
1

I figured it out. In large the problem I experienced was becasue I did the re-direction after I had piped the output of the command

snmpstatus -c public -v1 192.168.1.240

to grep then sed, at the end of quite a long one liner. I didn't realise at the time, although it's very obvious now, that the re-direction of any stderr or stdout has to happen immediately after the associated command. This is important becasue I had actually found the solution and discarded it as bizarrely not working, becasue I had tried to re-direct at the end of the pipe.

Here is how to re-direct the stderr to a variable

error=$(snmpstatus -c public -v1 192.168.1.240 2>&1)
echo $error

Here is an explanation of the syntax 0 = stdin 1 = stdout 2 = stderr > = redirect

Therefore 2>1 means redirect stderr to stdout. The & is essential therefore 2>&1 must be written, but in my reading I could not establish why.

This Stackoverflow answer was very helpful, and so was this very well written page on re-direction.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.