views:

56

answers:

3

netstat -an | grep hypen echo $variable hypen | wc -l

How to collect the value of netstat -an | grep echo $variable | wc -l to a varibale conn_count.

+1  A: 

Use backticks for maximum portability:

conn_count=`netstat -an | grep ${variable} | wc -l`

If you have a more modern shell such as bash, you can use $() instead:

conn_count=$(netstat -an | grep ${variable} | wc -l)

$() notation is better because it is easier to nest:

foo=$(netstat -an | grep $(head /path/fo/foo))
R Samuel Klatchko
$variable="abc|efg|xyz rst|ghf|tcg"for i in $variabledoConn_count=$(netstat -an | grep $(echo ${i} | cut -d'|' -f3) | wc -l)donewant to find the netstat of the third field and collect it to a varible
Kimi
A: 

Use the subshell "backticks" escape, if you want to be able to use it for sh, ash, and variants thereof:

thevariable=`netstat -an | grep echo $variable | wc -l`

If you will be guaranteed access to bash or zsh, you could use the $() syntax instead:

thevariable=$(netstat -an | grep echo $variable | wc -l)

I think the first one also works with (t)csh, but I'm not sure as I don't use them.

Bushman
A: 

This will do it for each value between pipe characters:

variable="abc|efg|xyz rst|ghf|tcg"
saveIFS=$IFS
IFS='|'
for i in $variable
do
    Conn_count=$(netstat -an | grep "$i" | wc -l)
done
IFS=$saveIFS

This will do it for only the third value:

variable="abc|efg|xyz rst|ghf|tcg"
saveIFS=$IFS
IFS='|'
i=($variable)
IFS=$saveIFS
Conn_count=$(netstat -an | grep "${i[2]}" | wc -l)
Dennis Williamson