[英]Assign the returned value of a function to a variable in unix shell script
[英]collect the value returned by netstat into a variable
netstat -an | grep hypen echo $變量hypen | wc -l
如何收集netstat -an的值? grep echo $variable
| wc -l表示變量conn_count。
使用反引號以實現最大的可移植性:
conn_count=`netstat -an | grep ${variable} | wc -l`
如果您擁有更現代的外殼(例如bash),則可以使用$()
代替:
conn_count=$(netstat -an | grep ${variable} | wc -l)
$()
表示法更好,因為它更易於嵌套:
foo=$(netstat -an | grep $(head /path/fo/foo))
如果您希望能夠將其用於sh,ash及其變體,請使用subshell“反引號”轉義符:
thevariable=`netstat -an | grep echo $variable | wc -l`
如果可以保證可以訪問bash或zsh,則可以使用$()
語法:
thevariable=$(netstat -an | grep echo $variable | wc -l)
我認為第一個也可以與(t)csh一起使用,但是我不確定,因為我不使用它們。
這將對管道字符之間的每個值執行此操作:
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
這將僅針對第三個值:
variable="abc|efg|xyz rst|ghf|tcg"
saveIFS=$IFS
IFS='|'
i=($variable)
IFS=$saveIFS
Conn_count=$(netstat -an | grep "${i[2]}" | wc -l)
或者,使用read
(不需要保存IFS
):
variable="abc|efg|xyz rst|ghf|tcg"
IFS='|' read -r field1 field2 field3 remainder <<< "$variable"
Conn_count=$(netstat -an | grep "$field3" | wc -l)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.