Search code examples
bashpowershellshellubuntuwindows-subsystem-for-linux

Getting different results when using shell operators -ne and !=


I wrote the below shell script, when using -ne it gives the result Synced but also with a warning message : integer expression expected.
When I use != it gives NotSynced...
Is PowerShell's datetime different than Ubuntu's datetime?! (Am I comparing integers with strings!?)

#!/bin/bash

WinTime=$(powershell.exe "& {get-date -UFormat '%Y/%m/%d %H:%M:%S'}")
WSLTime=$(date +"%Y/%m/%d %H:%M:%S")

echo "$WinTime"
echo "$WSLTime"

if [ "$WinTime" != "$WSLTime" ]; then
    echo "🪟  Windows: $WinTime"
    echo "🐧  WSL:    $WSLTime"
    echo "NotSynced"
else
    echo "Synced"
fi

Using !=: enter image description here Using -ne: enter image description here


Solution

  • The question's original issue was the difference between -ne and !=; this was addressed in comments.

    Once OP switched to using != this allowed the second issue to bubble to the top ... the != was evaulating as 'true' when the two strings appeared to be the same.

    This answer addresses the second issue ...


    I'm running bash in a cygwin environment (ie, under windows so I have access to powershell.exe).

    Running OP's code I also get the same results:

    Windows: 2023/02/07 09:32:47
    WSL:     2023/02/07 09:32:47
    NotSynced
    

    If we take a look at the actual contents of these 2 variables we see:

    $ echo "$WinTime" | od -c
    0000000   2   0   2   3   /   0   2   /   0   7       0   9   :   3   2
    0000020   :   4   7  \r  \n
    0000025
    
    $ echo "$WSLTime" | od -c
    0000000   2   0   2   3   /   0   2   /   0   7       0   9   :   3   2
    0000020   :   4   7  \n
    0000024
    

    Notice that $WinTime includes a trailing \r (windows/dos line ending) which is the result of running the Windows binary powershell.exe. This extra \r is causing the conditional to evaluate as 'true' and thus print NotSynced.

    OP will want to remove the trailing \r.

    I don't know enough about powershell to know if it has an option to disable the \r so I'll let tr remove the \r:

    WinTime=$(powershell.exe "& {get-date -UFormat '%Y/%m/%d %H:%M:%S'}" | tr -d '\r')
    

    We can see the \r no longer exists:

    $ echo "$WinTime" | od -c
    0000000   2   0   2   3   /   0   2   /   0   7       0   9   :   3   6
    0000020   :   2   2  \n
    0000024
    

    And now the conditional evaluates as 'false' and prints Synced.

    NOTE: the script could still report NotSynced in the scenario where the two time capture commands run just before/after a change in seconds