系统相关
首页 > 系统相关> > 使用Awk打印时,linux – 3300000/1024/1024为0?

使用Awk打印时,linux – 3300000/1024/1024为0?

作者:互联网

我有下面的shell脚本,它试图以GHz为单位计算CPU的频率.该脚本主要是在shellcheck cpu_freq.sh下瘦.问题是,它不打印cpu频率;它打印0:

$./cpu_freq.sh
CPU_FREQ: 0

下面我使用的是echo,但是我尝试了其他的东西,比如将文件系统密钥重定向到命令中,使用here文件和其他几个堆栈溢出.

该脚本打印0而不是值3.147.为什么脚本无法打印3.147左右?

这是一个脚本的痕迹.

$bash -x cpu_freq.sh
+ GREP=grep
+ AWK=awk
...
+ CPU_FREQ=0.5
+ [[ -e /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq ]]
++ cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
+ CPU_FREQ=3300000
++ echo 3300000
++ awk 'BEGIN {print $0/1024/1024; exit}'
+ CPU_FREQ=0
+ echo 'CPU_FREQ: 0'
CPU_FREQ: 0

这是脚本.

$cat -n cpu_freq.sh
 1  #!/usr/bin/env bash
 2
 3  GREP=grep
 4  AWK=awk
 5
 6  THIS_SYSTEM=$(uname -s 2>&1)
 7  IS_AIX=$(echo -n "$THIS_SYSTEM" | "$GREP" -i -c aix)
 8  IS_DARWIN=$(echo -n "$THIS_SYSTEM" | "$GREP" -i -c darwin)
 9  IS_SOLARIS=$(echo -n "$THIS_SYSTEM" | "$GREP" -i -c sunos)
10
11  # Benchmarks expect frequency in GiHz.
12  CPU_FREQ=0.5
13  if [[ (-e "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq") ]]; then
14          CPU_FREQ="$(cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq)"
15          CPU_FREQ="$(echo "$CPU_FREQ" | $AWK 'BEGIN {print $0/1024/1024; exit}')"
16  elif [[ (-e "/proc/cpuinfo") ]]; then
17          CPU_FREQ="$($GREP 'MHz' < /proc/cpuinfo | $AWK '{print $4; exit}')"
18          if [[ -z "$CPU_FREQ" ]]; then CPU_FREQ=512; fi
19          CPU_FREQ="$(echo $CPU_FREQ | $AWK 'BEGIN {print $0/1024}')"
20  elif [[ "$IS_DARWIN" -ne "0" ]]; then
21          CPU_FREQ="$(sysctl -a 2>&1 | $GREP "hw.cpufrequency" | $AWK '{print ($3); exit;}')"
22          CPU_FREQ="$(echo $CPU_FREQ | $AWK 'BEGIN {print $0/1024/1024/1024}')"
23  elif [[ "$IS_SOLARIS" -ne "0" ]]; then
24          CPU_FREQ="$(psrinfo -v 2>/dev/null | $GREP "MHz" | $AWK '{print $6; exit;}')"
25          CPU_FREQ="$(echo $CPU_FREQ | $AWK 'BEGIN {print $0/1024}')"
26  elif [[ "$IS_AIX" -ne "0" ]]; then
27          CPU_FREQ="$(prtconf -s 2>/dev/null | $GREP "MHz" | $AWK '{print $4; exit;}')"
28          CPU_FREQ="$(echo $CPU_FREQ | $AWK 'BEGIN {print $0/1024}')"
29  fi
30
31  echo "CPU_FREQ: $CPU_FREQ"

这是剩余的shellcheck警告.我相信这是预期的.

In cpu_freq.sh line 15:
    CPU_FREQ="$(echo "$CPU_FREQ" | $AWK 'BEGIN {print $0/1024/1024; exit}')"
                                        ^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.

解决方法:

BEGIN和END不接收字段值.

$awk 'BEGIN { print $0 / 1024 / 1024 ; exit }' <<< '3300000'
0
$awk '{ print $0 / 1024 / 1024 ; exit }' <<< '3300000'
3.14713

标签:linux,awk,text-processing
来源: https://codeday.me/bug/20190816/1665111.html