首页 > 解决方案 > 分配一个变量并在 if 语句 shell 脚本中使用它

问题描述

我是 shell 脚本的新手,正在尝试制作一些小脚本。当我试图写 if 条件时,我被卡住了。在下面的代码中,我试图从 df 获取 $5 值并尝试在 if 条件下使用它。但是代码不起作用。

 #!/bin/sh

temp = $(df -h | awk '$NF=="/"{$5}')
if [ $temp > 60 ] ; then
 df -h | awk '$NF=="/" {printf("%s\n"),$5}'
 (date -d "today" +"Date:%Y.%m.%d"" Hour: %H:%M")
fi

#end

所以我想出了一些东西并将我的代码更改为:

temp=$(df -h | awk '$NF=="/"{$5}')
if [ "$((temp))" -gt 0 ] ; then
 df -h | awk '$NF=="/" {printf("%s\n"),$5}'
 (date -d "today" +"Date:%Y.%m.%d"" Hour: %H:%M")
fi

#end

现在,我正在尝试获取 $5 变量的整数值。它返回一个百分比,我想将此百分比与 %60 进行比较。我怎样才能做到这一点 ?

标签: shell

解决方案


让我们看看 shellcheck.net 告诉我们什么:

Line 1:
  #!/bin/sh
^-- SC1114: Remove leading spaces before the shebang.

Line 3:
temp = $(df -h | awk '$NF=="/"{$5}')
     ^-- SC1068: Don't put spaces around the = in assignments.

Line 4:
if [ $temp > 0 ] ; then
     ^-- SC2086: Double quote to prevent globbing and word splitting.
           ^-- SC2071: > is for string comparisons. Use -gt instead.
           ^-- SC2039: In POSIX sh, lexicographical > is undefined.

嗯,好的,经过一点修复:

#!/bin/sh
temp=$(df -h | awk '$NF=="/"{$5}')
if [ "$temp" -gt 0 ] ; then  
   df -h | awk '$NF=="/" {printf("%s\n"),$5}'
   (date -d "today" +"Date:%Y.%m.%d"" Hour: %H:%M")
fi

命令与命令[ ... ]相同test。测试没有<数字比较。它有-gt(更大)。见人测试
这将现在运行,但绝对不是你想要的。您想要 df 输出的第五列,即。使用百分比。为什么需要 -h/人类可读的输出?我们不需要那个。你想要哪一行 df 输出?我猜你不想要标题,即。第一行:Filesystem 1K-blocks Used Available Use% Mounted on。让我们用磁盘名称过滤列,我选择 /dev/sda2。我们可以过滤第一个单词等于 /dev/sda2 的行grep "^/dev/sda2 "。我们需要用 获取第五列的值awk '{print $5}'。我们也需要去掉 '%' 符号,否则 shell 不会将值解释为数字,使用sed 's/%//'或更好tr -d '%'. 指定date -d"today"与 just 相同date。将命令包含(...)在子shell中运行它,我们不需要它。

#!/bin/sh
temp=$(df | grep "^/dev/sda2 " | awk '{print $5}' | tr -d '%')
if [ "$temp" -gt 0 ]; then  
   echo "${temp}%"
   date +"Date:%Y.%m.%d Hour: %H:%M"
fi

这很简单,如果磁盘 /dev/sda2 上的使用百分比高于 0,那么它将打印使用百分比并以自定义格式打印当前日期和时间。


推荐阅读