Unix: Why am I getting, "integer expression expected"?
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: [: : integ开发者_运维百科er expression expected
What is wrong with this? Is the for loop running in a separate process or something?
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.
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'.
In Bash, use:
(( x == 0 )) && echo "No valid files"
In POSIX shells:
[ ${x:-0} -eq 0 ] && echo "No valid files"
or initialize your variable as Jonathan shows.
精彩评论