2

I want to bring a bridge down only when the last port is removed and so I have this somewhat hokey check to do it

brctl show looks awkward to parse to get the information out and doesn't feel much better than what I have below. Is there a cleaner method?

 brctl_count_if()
 {
        local BRIDGE=$1

        if [ ! -d /sys/devices/virtual/net/$BRIDGE ]; then
            echo 0
            return
        fi

        /bin/ls -1 /sys/devices/virtual/net/$BRIDGE/brif 2>/dev/null | wc -l
 }

1 Answer 1

3

You can make it:

has_ports() {
  ls -A "/sys/devices/virtual/net/$1/brif/" 2> /dev/null | grep -q .
}

has_ports br0 || brctl delbr br0

Or:

if ! has_ports br0; then
  brctl delbr br0
fi

(note that you do need the -A as interface names are allowed to start with .).

To count the number of ports:

With zsh:

ports=(/sys/devices/virtual/net/$bridge/brif/*(DN:t))
printf '%s\n' "$#ports ports in $bridge"

(:t) to only have the file names instead of full paths.

With bash:

shopt -s nullglob dotglob
ports=("/sys/devices/virtual/net/$brige/brif/"*)
printf '%s\n' "${#ports[@]} ports in $bridge"

(note that ports contains the full paths as bash has no equivalent for zsh's :t).

Both would return 0 for a bridge that doesn't exist.

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.