错误“预期为整数表达式";在脚本中 [英] Error "integer expression expected" in script

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

问题描述

WBINFO="/usr/bin/wbinfo -t"
TMP="/tmp/winbind"
RESTART="/sbin/service winbind restart"
TXT="failed"


$WBINFO > $TMP
TARGET='cat $TMP |grep $TXT | wc -l'

if [ "$TARGET" -eq "1" ];
then
$RESTART
else
echo good

fi

我收到此错误:

line 10: [: cat $TMP |grep $TXT | wc -l: integer expression expected

推荐答案

TARGET='cat $TMP |grep $TXT | wc -l'

这将分配文字字符串'cat $ TMP | grep $ TXT |wc -l'到变量 $ TARGET .

This assigns the literal string 'cat $TMP |grep $TXT | wc -l' to the variable $TARGET.

看起来您想要的是命令的输出,该命令需要反引号:

It looks like what you want is the output of the command, which requires backticks:

TARGET=`cat $TMP |grep $TXT | wc -l`

,或者,如果您拥有相当现代的外壳,则使用 $(...)语法:

or, if you have a reasonably modern shell, the $(...) syntax:

TARGET=$(cat $TMP |grep $TXT | wc -l)

此外,从上面到现在,该命令可以大大简化:

Furthermore, that command can be simplified considerably, from the above to this:

TARGET=$(grep $TXT $TMP | wc -l)

对此:

TARGET=$(grep -c $TXT $TMP)

最后,如果您从中更改 if 语句,则可以完全消除 $ TARGET 变量:

Finally, the $TARGET variable can be eliminated altogether if you change the if statement from this:

if [ "$TARGET" -eq "1" ];

对此:

if [ $(grep -c "$TXT" "$TMP") = 1 ];

或者您可以使用 [[[ ... ]] 而不是 [ ... ] (是bash的首选).

Or you can use [[ ... ]] rather than [ ... ] (it's preferred for bash).

或者,如果您仅关心模式是否完全发生(而不是要求它只出现一次):

Or, if you only care whether the pattern occurs at all (rather than requiring it to appear exactly once):

if grep -q "$TXT" "$TMP";

为此,您也可以删除 $ TMP 文件;我将其保留为练习.8-)}

For that matter, you can eliminate the $TMP file as well; I'll leave that as an exercise. 8-)}

请咨询 grep 的文档,以了解选项的作用.( -c 选项告诉它打印匹配数量, -q 不打印任何内容,但仍会设置状态以指示是否找到了模式).

Consult the documentation for grep to see what the options do. (The -c option tells it to print the number of matches, -q prints nothing but still sets the status to indicate whether the pattern was found).

请注意,我还在变量引用周围添加了引号,如果有可能它们的值可能包含任何特殊字符,则这是一个好习惯.

Note that I also added quotation marks around the variable references, which is good practice if there's any possibility that their values might contain any special characters.

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

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