Bash错误:预期为整数表达式 [英] Bash error: Integer expression expected

查看:204
本文介绍了Bash错误:预期为整数表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的部分中,您将看到我试图在UNIX计算机上运行的Shell脚本以及脚本.

In the sections below, you'll see the shell script I am trying to run on a UNIX machine, along with a transcript.

当我运行该程序时,它会提供预期的输出,但同时也会显示笔录中显示的错误.可能是什么问题,我该如何解决?

When I run this program, it gives the expected output but it also gives an error shown in the transcript. What could be the problem and how can I fix it?

首先,脚本:

#!/usr/bin/bash

while read A B C D E F
do
    E=`echo $E | cut -f 1 -d "%"`
    if test $# -eq 2
    then
        I=`echo $2`
    else
        I=90
    fi
    if test $E -ge $I
    then
        echo $F
    fi
done

以及运行它的成绩单:

$ df -k | ./filter.sh -c 50
./filter.sh: line 12: test: capacity: integer expression expected
/etc/svc/volatile
/var/run
/home/ug
/home/pg
/home/staff/t
/packages/turnin
$ _

推荐答案

在显示以下内容的行之前:

Before the line that says:

if test $E -ge $I

临时放置行:

echo "[$E]"

,您会发现很多非数字内容,这是因为df -k的输出看起来像这样:

and you'll find something very much non-numeric, and that's because the output of df -k looks like this:

Filesystem     1K-blocks      Used Available Use% Mounted on
/dev/sdb1      954316620 212723892 693109608  24% /
udev               10240         0     10240   0% /dev
: :

有问题的行是第一行,它将第五个字段Use%转换为Use,这肯定是不是整数.

The offending line there is the first, which will have its fifth field Use% turned into Use, which is definitely not an integer.

一个快速的解决方法可能是将您的用法更改为:

A quick fix may be to change your usage to something like:

df -k | sed -n '2,$p' | ./filter -c 50

或:

df -k | tail -n+2 | ./filter -c 50

这些额外的过滤器(sedtail)将仅从第2行开始打印.

Either of those extra filters (sed or tail) will print only from line 2 onwards.

如果您完全不需要特殊的脚本,则可能会遇到类似这样的情况:

If you're open to not needing a special script at all, you could probably just get away with something like:

df -k | awk -vlimit=40 '$5+0>=limit&&NR>1{print $5" "$6}'

它的工作方式是仅在同时存在以下两种情况的行上进行操作:

The way it works is to only operate on lines where both:

  • 第五个字段,转换为数字,至少等于-v传递的限制;和
  • 记录号(行)是两个或更多.
  • the fifth field, converted to a number, is at least equal to the limit passed in with -v; and
  • the record number (line) is two or greater.

然后,它仅输出那些匹配行的相关信息.

Then it simply outputs the relevant information for those matching lines.

此特定示例输出文件系统的使用情况(以与42%类似的百分比),但是,如果您只想根据脚本使用文件系统,则只需更改print即可输出$6单独:{print $6}.

This particular example outputs the file system and usage (as a percentage like 42%) but, if you just want the file system as per your script, just change the print to output $6 on its own: {print $6}.

或者,如果您百分比但没有%,则可以使用与条件中相同的方法:{print $5+0" "$6}.

Alternatively, if you do the percentage but without the %, you can use the same method I used in the conditional: {print $5+0" "$6}.

这篇关于Bash错误:预期为整数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆