題目
小樓是一個(gè)系統(tǒng)管理員,需要編寫一個(gè)腳本 getinfo.sh 獲取 Linux 服務(wù)器的 CPU、內(nèi)存等信息。
腳本 getinfo.sh 腳本執(zhí)行時(shí)候不需要任何參數(shù),輸出的內(nèi)容包括以下信息:
$ bash getinfo.sh
cpu num: 2
memory total: 2.8G
memory free: 329M
disk size: 10G
system bit: 32
process: 32
software num: 944
ip: 192.168.1.9
注意上述每行內(nèi)容的冒號(hào)后都有一個(gè)空格。
其中包括的數(shù)據(jù)項(xiàng):
CPU數(shù)量(cpu num)
總內(nèi)存(memory total),單位為 G
可用內(nèi)存(memorty free),單位為 M
掛載到 / 根目錄的文件系統(tǒng)的總大?。╠isk size),單位為 G
系統(tǒng)位數(shù)(system bit)
當(dāng)前系統(tǒng)正在運(yùn)行的進(jìn)程數(shù)(process)
查看已安裝的軟件包數(shù)量(software num)
eth0的ip地址(ip)
目標(biāo)
腳本存放的路徑必須在 /home/shiyanlou/getinfo.sh
輸出的信息一共有 8 行,需要按照上面給出的示例的順序
腳本執(zhí)行過程及輸出信息需要滿足上述需求
提示
awk
sed
知識(shí)點(diǎn)
Linux 系統(tǒng)監(jiān)控命令
Linux 上文本處理命令
Linux 上軟硬件信息獲取
我的實(shí)現(xiàn)
#!/bin/bash
echo cpu num: $(cat /proc/cpuinfo |grep processor|wc -l)
free -h |grep Mem |awk '{printf "memory total: "$2 "\n" "memory free: "$4 "\n"}'
df -h |grep "/$" | awk '{printf "disk size: " $2 "\n"}'
echo system bit: $(getconf LONG_BIT)
echo process: $(ps -A |wc -l)
echo software num:$(dpkg -l |wc -l)
官方答案
#!/bin/bash
echo "cpu num:" `grep processor /proc/cpuinfo|wc -l`
echo "memory total:" `free -g|grep "Mem:"|awk '{print $2}'`G
echo "memory total:" `free -m|grep "Mem:"|awk '{print $4}'`M
echo "disk szie:" `df -h /|grep "/$"|awk '{print $2}'`
if [ `uname -m` = 'x86_64' ];then
echo "system bit: 64"
else
echo "system bit: 32"
fi
echo "process:" `ps axu|wc -l`
echo "software num:" `dpkg -l|wc -l`
echo "ip:" `ifconfig eth0|grep "inet "|awk '{print $2}'|awk -F":" '{print $2}'`
總結(jié)
echo "ip: " (ifconfig eth0|grep "inet "|awk '{print $2}'|awk -F":" '{print $2}')
我就卡在此處,它通過兩次使用awk 巧妙解決,很初級(jí),但我。。