bash Unix:为什么我会得到“预期的整数表达式”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4453838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:06:20  来源:igfitidea点击:

Unix: Why am I getting, "integer expression expected"?

bashunix

提问by Strawberry

for arg; do
        [ -f "$arg" ] && x=1 && continue                                                                                                                                       
        echo "Not a File" >&2
done

[ "$x" -eq 0 ] && echo "No valid files"

I am getting this error: [: : integer expression expected

我收到此错误: [: : integer expression expected

What is wrong with this? Is the for loop running in a separate process or something?

这有什么问题?for 循环是否在单独的进程中运行?

回答by Jonathan Leffler

Probably because 'x' is unset, so the comparison is between an empty string converted to an integer and zero. It isn't happy about the empty string.

可能是因为 'x' 未设置,所以比较是在转换为整数的空字符串和零之间进行的。它对空字符串不满意。

To fix

修理

x=0
...loop as now...
[ $x -eq 0 ] ...

This has the beneficial side-effect of reducing the number of ways your code can break if someone exports the environment variable 'x'.

如果有人导出环境变量“x”,这具有减少代码破坏方式的有益副作用。

回答by Paused until further notice.

In Bash, use:

在 Bash 中,使用:

(( x == 0 )) && echo "No valid files"

In POSIX shells:

在 POSIX shell 中:

[ ${x:-0} -eq 0 ] && echo "No valid files"

or initialize your variable as Jonathan shows.

或者像 Jonathan 展示的那样初始化你的变量。