确定一个变量并在if语句shell脚本中使用它

时间:2018-06-12 18:27:33

标签: shell

我是shell脚本的新手,并尝试制作一些小脚本。当我试着写条件时,我卡住了。在下面的代码中,我试图从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进行比较。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

让我们看看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(大于)。见man test
这将立即运行,但绝对不能做你想要的。你想要第五列df输出,即。使用百分比。为什么需要-h /人类可读输出?我们不需要那个。你想要哪一排df输出?我想你不想要标题,即。第一行:Filesystem 1K-blocks Used Available Use% Mounted on。让我们用光盘名称过滤列,我选择/ dev / sda2。我们可以使用grep "^/dev/sda2 "过滤第一个单词等于/ dev / sda2的行。我们需要使用awk '{print $5}'获取第五列的值。我们需要摆脱&#39;%&#39;也是一个符号,否则shell不会将值解释为数字,sed 's/%//'或更好的tr -d '%'。指定date -d"today"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,那么它将打印使用百分比并以自定义格式打印当前日期和时间。

答案 1 :(得分:0)

假设您正在使用GNU工具,您可以将df输出缩小到您所需的范围:

pct=$( df --output=pcent / | grep -o '[[:digit:]]\+' )
if [[ $pct -gt 60 ]]; then ...