EUS
EUS

Reputation: 422

Can't verify result from SSH

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 [email protected] "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.

Upvotes: 1

Views: 42

Answers (1)

0stone0
0stone0

Reputation: 43904

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 [email protected] "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 [email protected] "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

Upvotes: 2

Related Questions