处理do语句中的异常



请,我正在尝试创建以下脚本:

..
do
PID=$(echo $i | cut -d: -f1)
THREADS=$(cat /proc/$PID/status | grep -i "Threads" | awk '{print $2}')
done
..

但是有时候,有些进程没有这样的文件状态创建。那么,当我在执行脚本

时得到这个消息时,我该如何处理这样的异常呢?美元。/check_memory.shcat:/proc/9809/status: No such file or directory$

所以,我需要像这样打印这个消息:

Memory Usage Per Process
----------------------------------------
PID       THREADS                                              
9936      129                                                       
9809      There is no status file for this process   

感谢您的支持!感谢您的支持

您可以使用以下sh脚本:

#!/bin/sh
cat<<EOF
Memory Usage Per Process
----------------------------------------
PID     THREADS
EOF
for pid in 999 $$; do
threads=$(awk '/Threads/{print $2}' "/proc/$pid/status" 2>/dev/null) ||
threads='There is no status file for this process'
printf '%bn' "$pidt$threads"
done
输出:

Memory Usage Per Process
----------------------------------------
PID       THREADS
999       There is no status file for this process
345234    1

编辑了评论中问题的脚本

#!/bin/sh
printf "%-10s%-10s%sn" "PID" "THREADS"
function sysmon_main() {
pids=( $(ps -o pid ax | awk 'NR>1') )
for pid in "${pids[@]}"; do
threads=$(awk '/Threads/{print $2}' "/proc/$pid/status" 2>/dev/null) ||
threads='There is no status file for this process'
printf "%-10s%-10s%sn" "$pid" "$threads"
done
}
sysmon_main | sort -bnr -k2

最新更新