开发者

collect the value returned by netstat into a variable

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

How to collect the value of netstat -an 开发者_如何学C| grep echo $variable | wc -l to a varibale conn_count.


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))


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.


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)

Or, using read (IFS doesn't need to be saved):

variable="abc|efg|xyz rst|ghf|tcg"
IFS='|' read -r field1 field2 field3 remainder <<< "$variable"
Conn_count=$(netstat -an | grep "$field3" | wc -l)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜