从 BASH 脚本中的变量中删除字符

Removing character from variable in BASH script

我有一个使用 SaltStack 命令行以及 BASH 命令的脚本。该脚本用于从多个 Linux 服务器(因此是 SaltStack)收集数据,我想收集的检查之一是磁盘 space.

我使用以下命令完成了此操作:

salt $i cmd.run 'df -Ph / | tail -n1 | awk '"'"'{ print }'"'"'' | grep -v $i

$i = hostname 和丑陋的 '"'"' 的使用是为了让我的命令可以通过 SaltStack 运行 因为 Salt 的远程执行功能需要命令周围的单引号,如果我把它们留在我的命令不会 运行 在我的 BASH 脚本中。

示例语法:

salt $hostname cmd.run 'command here'

在这里和同事提出许多问题后,我对脚本的这一部分进行了排序。但是,我现在的问题是剥离上述命令的输出以删除 'G' 以便我的脚本可以将输出与我定义的阈值进行比较并将此脚本正在管道化的 HTML 变为红色.

阈值:

diskspace_threshold=5

命令:

while read i ; do
diskspace=`salt $i cmd.run 'df -Ph / | tail -n1 | awk '"'"'{ print }'"'"'' | grep -v $i`

验证检查:

if [[ "${diskspace//G}" -lt $diskspace_threshold ]]; then
    ckbgc="red"
fi

我用来去除 G 的方法在命令行上有效,但在我的脚本中不起作用,所以它一定与语法有关,或者只是它现在在脚本中的事实。任何 ideas/thoughts 都会有所帮助。

干杯!

编辑:这是我在 运行 运行我的脚本时收到的错误消息: serverdetails.sh:第 36 行:p : 2.8: 语法错误:无效算术运算符(错误标记为“.8”)

我假设错误来自这里(这是第 36 行吗?)

if [[ "${diskspace//G}" -lt $diskspace_threshold ]]; then

注意错误信息:

serverdetails.sh: line 36: p : 2.8: syntax error: invalid arithmetic operator (error token is ".8")

bash不做浮点运算

$ [[ 2.8 -lt 3 ]] && echo OK
bash: [[: 2.8: syntax error: invalid arithmetic operator (error token is ".8")

您需要执行以下操作:

result=$( bc <<< "${diskspace%G} < $diskspace_threshold" )
if [[ $result == 1 ]]; then
  echo OK
else
  echo Boo
fi