linuxbashnetwork-programmingifconfig

Separately handling case when both of two items are present (grepping ifconfig output)


I am trying to pipe a script to my statusbar in linux via dwm window manager and have it working fine but wanted to have a command echo "multiple" if i have more than one interface name up at the same time. This is what i have come up with so far but it doesnt want to echo "multiple" when running the script if wlan0 and usb0 are up at the same time? any help much appreciated.

#!/bin/bash

a=$(ifconfig | grep -ow "wlan0")
b="wlan0"

c=$(ifconfig | grep -ow "usb0")
d="usb0"

e=$(ifconfig | grep -ow 'usb0\|wlan0')
f="usb0\nwlan0"


if   [[ "$a" == "$b" ]] ; then
        echo -e "${b}"

elif [[ "$c" == "$d" ]] ; then
        echo -e "${d}"

elif [[ "$e" == "$f" ]] ; then
        echo "multiple"

else
        echo "not connected"
fi

Solution

  • Put the multiple case first, and only fall through to the others if it isn't reached.

    #!/usr/bin/env bash
    isup() {
      [[ -e /sys/class/net/$1/carrier ]] || return 1
      [[ $(</sys/class/net/$1/carrier) = 1 ]] || return 1
      return 0
    }
    
    if isup usb0 && isup wlan0; then
      echo "multiple"
    elif isup usb0; then
      echo "usb0"
    elif isup wlan0; then
      echo "wlan0"
    fi
    

    This also doesn't require we have ifconfig (which isn't present in all new Linux distros -- the modern replacement is iproute2, providing the ip command), and moreover avoids running any external commands (much less running two separate external commands three times each).