bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Please advise on bash programming tactics/strategy


From: Bob Proulx
Subject: Re: Please advise on bash programming tactics/strategy
Date: Tue, 11 Dec 2007 22:31:47 -0700
User-agent: Mutt/1.5.13 (2006-08-11)

cga2000 wrote:
> I was wondering if there is any way I can convince netstat to return
> its output to bash variables for additional processing.

Do you mean like this?

    rxcnt=$(netstat -ni | awk '/^eth0/{print$4}')

> Pretty simple logic:
> 
> Do forever:
> 
>   Call netstat to obtain RX & TX byte counts for eth0
>   Print delta {current .. minus previous .. byte counts}
>   Save current byte counts 
>   Wait for a second or so ..

Such as like this?

  #!/bin/sh

  interface=eth0

  prevrxcnt=0
  rxcnt=0
  diffcnt=0

  get_data()
  {
    netstat -ni | awk '/^'"$interface"'/{print$4}'
  }

  init_data()
  {
    prevrxcnt=$(get_data)
  }

  save_data()
  {
    rxcnt=$(get_data)
    diffrxcnt=$(($rxcnt - $prevrxcnt))
    prevrxcnt=$rxcnt
  }

  init_data
  while sleep 5; do
    save_data
    echo $diffrxcnt
  done

  exit 0

I would not normally use global variables like this but it was
specifically what you were asking so I used them.  Normally I prefer
to avoid global variables except for global configuration data.  Being
able to trace the flow through the code as you read it is very
important to the long term maintainability IMNHO.  So generally I
advise to write the code such as to avoid using globals.

> I initially thought I could just pipe the "netstat -in" command to the
> invocation of a bash function.

Yes?

  filter_data() { awk '/^'"$interface"'/{print$4}' ;}

  get_data() { netstat -ni | filter_data ;}

> The function would have taken care of the gory details of parsing &
> formatting the output of the netstat command and then stored the current
> byte counts where they would be available for the next time the function
> is invoked.

Oh, stored, global variables, blech, but okay.

  grab_data() { prevrxcnt=$(awk '/^'"$interface"'/{print$4}') ;}

> The trouble is that I haven't been able to find anything like a "static"
> local variable -- ie. variables that are not reinitialized every time
> the function is invoked.

In C static variables are global to the compilation unit.  In bash the
entire script is the compilation unit.  In C static variables are not
visible across compilation units.  In bash there is no individual
compilation with a separate link step.

Traditionally a naming convention such as applying the name of the
function to the variable name is used to make sure that name
collisions are avoided.

> Is there such a thing?
> Or is there any way the function could save the current byte counts to
> global variables?  

See my examples.  Or did I miss the point of the question entirely?

Bob




reply via email to

[Prev in Thread] Current Thread [Next in Thread]