I\'m trying to get the default gateway, using the destination 0.0.0.0
I used this command: netstat -rn | grep 0.0.0.0
And it return
For a list of all default gateways, use mezgani's answer, duplicated (and slightly simplified) here:
/sbin/ip route | awk '/^default/ { print $3 }'
If you have multiple network interfaces configured simultaneously, this will print multiple gateways. If you want to select a single known network interface by name (e.g. eth1), simply search for that in addition to filtering for the ^default lines:
/sbin/ip route |grep '^default' | awk '/eth1/ {print $3}'
You can make a script that takes a single network-interface name as an argument and prints the associated gateway:
#!/bin/bash
if [[ $# -ne 1 ]]; then
echo "ERROR: must specify network interface name!" >&2
exit 1
fi
# The third argument of the 'default' line associated with the specified
# network interface is the Gateway.
# By default, awk does not set the exit-code to a nonzero status if a
# specified search string is not found, so we must do so manually.
/sbin/ip route | grep '^default' | awk "/$1/ {print \$3; found=1} END{exit !found}"
As noted in the comments, this has the advantage of setting a sensible exit-code, which may be useful in a broader programmatic context.