shell - 分配一个变量并在 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 进行比较。我怎样才能做到这一点 ?
解决方案
让我们看看 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,那么它将打印使用百分比并以自定义格式打印当前日期和时间。
推荐阅读
- c# - C# 使用 SharpZipLib 将文本文件 (.GetInputStream()) 从存档解压缩为字符串
- python-3.x - 在 Python 中的 Scrapy 中导入模块时出错
- java - 拜托,如果我们想在主方法之外的方法中使用它,你能告诉我第二次声明扫描器类对象的原因吗?
- css - 不同项目文件夹中的 SCSS 文件被编译成一个 CSS 文件
- javascript - 当我在 JS fike 中添加 CSS 类时,它没有运行
- c# - Asp.net Core 3.1 MVC - 在开发环境中禁用身份验证
- r - R如何按行值分组,拆分或子集
- javascript - swiper.js 自定义上一个和下一个按钮在点击时不起作用
- html - 获取单选按钮的值并将其用于计算的问题
- java - 在 JAVA 中保存 h264 文件有效,但在 android 中保存损坏的文件