简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM