用awk打印时3300000/1024/1024是0?

用awk打印时3300000/1024/1024是0?

我有下面的 shell 脚本,它尝试计算 CPU 的频率(以 GHz 为单位)。剧本大多是精简的shellcheck cpu_freq.sh。问题是,它不打印cpu频率;它打印 0:

$ ./cpu_freq.sh
CPU_FREQ: 0

下面我使用的是echo,但我也尝试了其他操作,例如将文件系统密钥重定向到命令中,使用此处文件和堆栈溢出中的其他几个文件。

该脚本打印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.

答案1

BEGIN并且END不接收字段值。

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

相关内容