我正在编写一个简单的 bash 脚本来显示系统信息。这是我的代码:
#!/bin/bash
hostn=$(hostname)
system=$(uname -a)
cpu=$(cat /proc/cpuinfo | grep "model name" | cut -d : -f 2)
disk=$(df -h | grep -v "tmpfs" | awk '{print $1 " " $4}')
printf -v serverinfo "Hostname:\t%s\nCPU:\t%s\nDisk:\t%s\nSystem:t%s\n" $hostn $cpu $disk $system
echo "$serverinfo"
显示的结果格式不正确:
Hostname: KASH1LFCE01
CPU: Intel(R)
Disk: Xeon(R)
System:tCPU
Hostname: E5-2650
CPU: v3
Disk: @
System:t2.30GHz
Hostname: Filesystem
CPU: Avail
Disk: /dev/sdc
System:t12G
Hostname: /dev/sda1
CPU: 431M
Disk: Linux
System:tKASH1LFCE01
Hostname: 2.6.32-642.1.1.el6.x86_64
CPU: #1
Disk: SMP
System:tTue
Hostname: May
CPU: 31
Disk: 21:57:07
System:tUTC
Hostname: 2016
CPU: x86_64
Disk: x86_64
System:tx86_64
Hostname: GNU/Linux
CPU:
Disk:
System:t
CPU信息分行打印,与uname -a信息相同。
答案1
引用变量,否则空格将导致它们被分成单独的参数。
printf -v serverinfo "Hostname:\t%s\nCPU:\t%s\nDisk:\t%s\nSystem:\t%s\n" "$hostn" "$cpu" "$disk" "$system"
通常,您应该始终引用变量,除非您知道需要将它们拆分为单词。