check if interface eth0 is up (configured)
You can do it many ways. Here an example:
$ cat /sys/class/net/eth0/operstate
up
ip a show ethX up
If nothing displayed then your interface is down
ip a | grep -Eq ': eth0:.*state UP' || _do_your_thing
So here we grep
the ubiquitous ip
tool's stdout
for a line which contains both our interface of interest and the phrase "state UP" ( thanks to @Lekensteyn for pointing out the need for a little more specificity than just UP
). We use the argument a
as the short form for address
and that should be enough to get a listing of all configured network cards in system.
One advantage to using ip
could be that it really should be available everywhere - it is how I commonly configure my Android phone's network devices, for instance.
The :colons
are used to avoid partial matches - in this way we guarantee a match for eth0
as opposed to an otherwise possible someothereth0
or eth007
.
Thanks @RaphaelAhrens for nudging me toward correctness and explaining my solution.
EDIT:
To handle the current requirements you could:
ip a | sed -rn '/: '"$if"':.*state UP/{N;N;s/.*inet (\S*).*/\1/p}'
The above will only print a CIDR ip address if your target $if
is UP, plugged in, and has one. For ipv6 the solution is just as simple with only minor modification.
If you don't like sed
you could achieve similar results with another |pipe ... grep
and adding a -A
context option to the first grep
- but I like sed
.