supress iproute2 error message

iproute2 has a message on fail that I do not know how to suppress.

I want to save the output of iproute2 to a variable for later use. if my network is up all is well and the output is something like:

sudo ip link set wlan0 up
ROUTE=$(ip route get 8.8.8.8)
printf "Route is:\n${ROUTE}"
Route is:
8.8.8.8 via 192.168.1.1 dev wlan0 src 192.168.1.17 uid 1000
    cache

If my network is down I get an unwanted artifact:

sudo ip link set wlan0 down
ROUTE=$(ip route get 8.8.8.8)
printf "Route is:\n${ROUTE}"
RTNETLINK answers: Network is unreachable
Route is:

So I am not sure what is producing the message RTNETLINK answers: Network is unreachable, or how to suppress this message.


The message is produced par ip on the standard error output.

In your terminal, both standard output and standard error output are printed in the terminal.

With var=$(command ...) syntax, you get ony the standard output in the variable but error output will printed by terminal.

You can redirect the error output to trash with 2>/dev/null after the command. like this:

ROUTE=$(ip route get 8.8.8.8 2>/dev/null)

Why 2? On POSIX systems (UNIX and Linux), 1 is the default number for standard output and 2 is for error output. 0 is for standard input.