我是shell脚本的新手,我正在尝试获取进程的内存和CPU利用率。将来我将从java程序运行此脚本,以便我可以获得该java程序的所有子进程的利用率。我的脚本目前看起来像
#!/bin/bash
# get the process Id of the program executing this shell script
ID=$PPID
echo the process id of the parent of this script is $ID
#fetch the parent of the program which executed this shell
PID=`ps -o ppid=$ID`
echo the grand parent id of the script is $PID
# traverse through all children and collect there memory/cpu utiliation information
for p in `pgrep -P $PID`; do
top -c -n 1 -p $p > /tmp/stat.log
done
现在当我运行这个程序时,我得到了以下输出
the process id of the parent of this script is 5331
the grand parent id of the script is 5331 3173 5331 6174
top: bad pid 'Usage:'
top: bad pid 'pgrep'
top: bad pid '[-flvx]'
top: bad pid '[-d'
top: bad pid 'DELIM]'
top: bad pid '[-n|-o]'
top: bad pid '[-P'
top: bad pid 'PPIDLIST]'
top: bad pid '[-g'
top: bad pid 'PGRPLIST]'
top: bad pid '[-s'
top: bad pid 'SIDLIST]'
top: bad pid '[-u'
top: bad pid 'EUIDLIST]'
top: bad pid '[-U'
top: bad pid 'UIDLIST]'
top: bad pid '[-G'
top: bad pid 'GIDLIST]'
top: bad pid '[-t'
top: bad pid 'TERMLIST]'
top: bad pid '[PATTERN]'
请有人帮助我。
答案 0 :(得分:1)
PID=`ps -o ppid=$ID` should have had a space between `ppid=` and `$ID`.
正确的形式(引用充分的论据,更喜欢$()
反对):
PID=$(ps -o ppid= "$ID")
但是这不会削减输出上的前导空间。正如我的建议,使用阅读:
read PID < <(exec ps -o ppid= "$ID")
或者,如果您愿意,可以使用egrep
修剪空间:
PID=$(ps -o ppid= "$ID" | egrep -o '\S+')
使用扩展模式匹配可能很复杂:
shopt -s extglob
PID=$(ps -o ppid= "$ID")
PID=${PID##+([[:blank:]])}
for
行也可以更好地完成:
while read -u 4 P; do
top -c -n 1 -p "$P" > /tmp/stat.log
done 4< <(exec pgrep -P "$PID")
我认为您打算将输出重定向到/tmp/stat.log
作为块:
while read -u 4 P; do
top -c -n 1 -p "$P"
done 4< <(exec pgrep -P "$PID") > /tmp/stat.log