开发者

if statement error bash

Please help me to find problem

t1=$(sort -k 2,2 f.txt|head -1|cut -d" " -f3)
while read x
do
t2=$(echo $x|cut -d" " -f2)
if [ $t2 -ge $t1 ] ; then
  p=$(echo $x|cut -d" " -f1)
  echo -n $p " "
fi
done <f.txt

f.txt

F1 13
G 13
H 0

I am geeting following error

开发者_如何学编程-sbash: [: 13: unary operator expected
-sbash: [: 13: unary operator expected

without H 0 row it work correct


'unary operator expected' is the error when you use a binary operator with only a single operand.

This means that either t2 or t1 is empty. To cause an empty variable to not disappear, use default notation ${VARIABLE:-DEFAULT} to give them a default value:

if [ ${t2:-0} -ge ${t1:-0} ]; then


you are using bash, so use bash's internals. No need to call external cut etc. also quote your variables when you use [ ]

set -- $(sort -k 2,2 f.txt|head -1)
t1=$3
while read f1 f2 f3
do
t2="$f2"
if [ "$t2" -ge "$t1" ] ; then
  p=$f1
  echo -n $p " "
fi
done <f.txt


I think you want

t1=$(sort -k 2,2 f.txt|head -1|cut -d" " -f2)

instead of

t1=$(sort -k 2,2 f.txt|head -1|cut -d" " -f3)

Your f.txt has only two fields, so cut command results in nothing, and then you pass that to [ ].

About why it works without the H 0 line, I suspect that your F line is

F 1 13

instead of

F1 13

(This is all just a guess.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜