Skip to content

Instantly share code, notes, and snippets.

@naranyala
Created May 22, 2024 09:17
Show Gist options
  • Select an option

  • Save naranyala/7d4d1b5bb34af0bda2a0cf961347f4bd to your computer and use it in GitHub Desktop.

Select an option

Save naranyala/7d4d1b5bb34af0bda2a0cf961347f4bd to your computer and use it in GitHub Desktop.
"select" to switch net interface and "monitor" to watch your net speed
#!/bin/bash
# Temporary file to store the selected interface
INTERFACE_FILE="/tmp/selected_network_interface"
# Function to get available network interfaces
get_interfaces() {
ls /sys/class/net | grep -v lo
}
# Function to check internet connectivity
check_internet() {
ping -c 1 google.com > /dev/null 2>&1
return $?
}
# Function to safely get network statistics
get_stat() {
local stat_file=$1
if [ -f "$stat_file" ]; then
cat "$stat_file"
else
echo 0
fi
}
# Function to monitor network speed
monitor_speed() {
INTERFACE=$1
# Get initial download and upload bytes
RX1=$(get_stat "/sys/class/net/$INTERFACE/statistics/rx_bytes")
TX1=$(get_stat "/sys/class/net/$INTERFACE/statistics/tx_bytes")
# Wait for one second
sleep 1
# Get new download and upload bytes
RX2=$(get_stat "/sys/class/net/$INTERFACE/statistics/rx_bytes")
TX2=$(get_stat "/sys/class/net/$INTERFACE/statistics/tx_bytes")
# Calculate bytes transferred in the interval
RXBPS=$(($RX2 - $RX1))
TXBPS=$(($TX2 - $TX1))
# Convert bytes per second to kilobytes per second
RXKBPS=$(echo "scale=2; $RXBPS/1024" | bc)
TXKBPS=$(echo "scale=2; $TXBPS/1024" | bc)
# Output the speeds
echo " $RXKBPS kB/s  $TXKBPS kB/s"
}
# Function to select network interface
select_interface() {
INTERFACE=$(get_interfaces | rofi -dmenu -p "Select Network Interface:")
if [ -z "$INTERFACE" ]; then
echo "No interface selected"
exit 1
fi
echo $INTERFACE > $INTERFACE_FILE
}
# Function to read interface from the temporary file
read_interface() {
INTERFACE=$(cat $INTERFACE_FILE)
if [ -z "$INTERFACE" ]; then
echo "No interface selected"
exit 1
fi
}
# Main script
if [ "$1" == "monitor" ]; then
if [ ! -f "$INTERFACE_FILE" ]; then
echo "No network interface selected. Please run './script.sh select' first."
exit 1
fi
read_interface
monitor_speed $INTERFACE
elif [ "$1" == "select" ]; then
select_interface
else
echo "Usage: $0 [monitor|select]"
exit 1
fi
# [module/net-speed]
# type = custom/script
# exec = ~/.config/polybar/_shared_scripts/net-speed.sh monitor
# click-left = ~/.config/polybar/_shared_scripts/net-speed.sh select
# interval = 2
# label = "%output%"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment