Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an output to the result in a while loop Bash

I’m trying to sum all bytes in "RX packets" lines of an ifconfig | grep "RX packets" output.

How do I do that?

Here’s my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/usr/lib/env bash

clear

result=0

while read i; do

    line=${i##*'bytes'} | awk '{print $1;}' 
    
    (( "$result"+="$line" ))

    echo "$result"

done <<< "$(ifconfig | grep "RX packets")"

Also: How should I extract those lines of bytes in a better way, doing "$(ifconfig | grep "RX packets")" and then line=${i##*'bytes'} | awk '{print $1;}' seems so ugly and complicated

if config | grep "RX packets" my output:

        RX packets 7817232  bytes 9337993347 (9.3 GB)
        RX packets 1240058  bytes 83114376 (83.1 MB)
        RX packets 0  bytes 0 (0.0 B)
        RX packets 188707  bytes 27682805 (27.6 MB)

Desired result – sum of all bytes:

9337993347 + 83114376 + 27682805

>Solution :

When assigning to a variable, even inside an arithmetic expression, use the variable name without the dollar sign.

When reading from a command list, use process substitution rather than a here string.

Also, you don’t need awk, you can remove the substring similarly to how you removed the other part.

#! /bin/bash
result=0

while read line; do

    line=${line##*bytes}  # Remove everything up to bytes.
    line=${line%(*}       # Remove everything starting from (.
    
    (( result+="$line" ))
done < <(ifconfig | grep "RX packets")
echo $result
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading