1

I'm verifying matches of a file via SSH to a host ubunty system, and the if statement is not correctly processing the result.

export FILENAME=test.txt
export NUM=$(ssh -t ubuntu@192.168.XXX.XXX "ls ~/Documents/ | grep '$FILENAME' | wc -l")
echo "Received value: $NUM"
if [ $NUM == 0 ]; then
    echo "If processed as: 0"
else
    echo "If processed as: 1"
fi

So if $FILENAME exists, I get the following output

Connection to 192.168.XXX.XXX closed.
Received value: 1
If processed as: 1

And if not, I get the following one

Connection to 192.168.XXX.XXX closed.
Received value: 0
If processed as: 1

Why may this be happening? Am I getting a wrong formatted value? If I force before the if statement NUM=0 or NUM=1 it gets correctly processed.

EUS
  • 422
  • 3
  • 16
  • 1
    Try with -eq rather than == – tomgalpin Feb 27 '20 at 10:57
  • I get the following error: `: integer expression expected1`. Anyway, if I set `NUM=0` before the if statement, it works both with `==` or `-eq`. Why may this happen? – EUS Feb 27 '20 at 11:03
  • Likely because you are returning more than just a "0" from the SSH command, i.e new line characters or something – tomgalpin Feb 27 '20 at 11:09

1 Answers1

2

if [ $NUM == 0 ]; then should work as expected. (More info on SO)


Use cat -v to show all invisible chars in your output;

NUM=$(ssh -t ubuntu@192.168.XXX.XXX "ls ~/Documents/ | grep '$FILENAME' | wc -l")
echo "NUM: ${NUM}" | cat -v

#Prints; NUM: 0^M

The invisible ^M char is messing with the if statement. Remove if from the result by piping through tr -d '\r'


export FILENAME=test.txt
export NUM=$(ssh -t ubuntu@192.168.XXX.XXX "ls ~/Documents/ | grep '$FILENAME' | wc -l" | tr -d '\r')
echo "Received value: $NUM"
if [ $NUM == 0 ]; then
    echo "If processed as: 0"
else
    echo "If processed as: 1"
fi

More ^M info;

  1. What is ^M
  2. Remove ^M from variable
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Just as a bit more info the ^M is added because the SSH has been requested with tty (-t) – tomgalpin Feb 27 '20 at 11:12
  • 1
    Wow. I knew it should be related to a hidden character or something, but no idea which one or how to display it. Really nice answer, worked perfectly. Thanks! – EUS Feb 27 '20 at 11:18