String comparison not Working properly

2020-02-13 04:23发布

My code:

x=$(awk -v i=$h -v j=17 'FNR == i {printf "%s ", $j}' newiptables.log)
s="SPT=80"

The log file referenced is:

Dec 26 09:17:51 localhost kernel: IN=eth0 OUT= MAC=00:10:c6:a8:da:68:00:90:7f:9c:50:5a:08:00 SRC=198.252.206.16 DST=10.128.1.225 LEN=313 TOS=0x00 PREC=0x00 TTL=64 ID=59334 PROTO=TCP SPT=80 DPT=56506 WINDOW=46535 RES=0x00 ACK PSH URGP=0 
Dec 26 09:17:52 localhost kernel: IN=eth0 OUT= MAC=00:10:c6:a8:da:68:00:90:7f:9c:50:5a:08:00 SRC=198.252.206.16 DST=10.128.1.225 LEN=1440 TOS=0x00 PREC=0x00 TTL=64 ID=47303 PROTO=TCP SPT=80 DPT=56506 WINDOW=46535 RES=0x00 ACK URGP=0 
Dec 26 09:17:52 localhost kernel: IN=eth0 OUT= MAC=00:10:c6:a8:da:68:00:90:7f:9c:50:5a:08:00 SRC=198.252.206.16 DST=10.128.1.225 LEN=1440 TOS=0x00 PREC=0x00 TTL=64 ID=47559 PROTO=TCP SPT=80 DPT=56506 WINDOW=46535 RES=0x00 ACK URGP=0

Then the next condition in the script needs to be checked is:

if [[ "$x" == "$s" ]]
then 
 < process if condition is true>
else
 < process if condition is false>
fi

The if condition is not working

标签: linux bash
2条回答
手持菜刀,她持情操
2楼-- · 2020-02-13 05:11

Necessary fix:

s="SPT=80"   # Not STP=80

This has since been fixed in the question.

Probably necessary fix:

if [[ "$x" == "$s" ]]  # Space between if and [[ highly recommended
then : it matches
else : it does not match
fi

As noted in the comments, the use of "%s " with a trailing space in the awk script means that the trailing space is stored in "$x" and this will break the comparison with "$s".

查看更多
小情绪 Triste *
3楼-- · 2020-02-13 05:15

Observe your awk command:

printf "%s ", $j

You print a trailing space due to which the test if [[ "$x" == "$s" ]] fails.

Eliminate the space from the printf:

printf "%s", $j

Alternatively, you could use the binary operator =~ (depending upon your need, of course):

if [[ "$x" =~ "$s" ]]
查看更多
登录 后发表回答