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