How can I toggle an interface every second in a Bash loop?
-
16-06-2021 - |
Question
I want to put an interface down and up every 1 second for 80 times, how can I implement this by a bash script?
Something like this?
COUNT = 80
for n in $(seq -w 1 $COUNT); do
case $n in
[1,3,5,7,9....79]*) # I don't know how to represent the odd value only
ifconfig veth1 down
sleep 1
;;
[2,4,6,8,10....80]*)
ifconfig veth1 up
sleep 1
;;
esac
done
Solution
COUNT=40
for n in $(seq -w 1 $COUNT); do
ifconfig veth1 down
sleep 1
ifconfig veth1 up
sleep 1
done
Or if you really want to count to 80:
COUNT=80
for n in $(seq -w 1 $COUNT); do
case $n in
*[13579])
ifconfig veth1 down
;;
*)
ifconfig veth1 up
;;
esac
sleep 1
done
OTHER TIPS
Toggle a flag:
#!/bin/bash
for ((i = 1, flag = 0; i <= 80; i++))
do
if ((flag ^= 1))
then
ifconfig veth1 down # odd
else
ifconfig veth1 up
fi
sleep 1
done
use % operator. like the following, replace the echo with the commands you want
count=0
while [ $count -lt 80 ]
do
if (( $count % 2 == 0 ))
then
echo 'aaa'
else
echo 'bbb'
fi
count=$(( $count + 1 ))
done
If you don't mind the bashisms, you can make your code much more concise through the use of various expansions available in Bash. For example:
for i in {1..80}; do
case $((i % 2)) in
0) ifconfig veth1 down ;;
1) ifconfig veth1 up ;;
esac
sleep 1
done
The magic here is the {1..80}
sequence expression, coupled with the modulo operator to determine whether the number is odd or even. If your version of Bash doesn't support sequence expressions for any reason, just use $(seq 1 80)
instead.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow