Last active
February 8, 2023 10:23
-
-
Save 411A/36de769d702087100f8d45a453517fae to your computer and use it in GitHub Desktop.
Fix WSL2 & Windows 11 Time Syncing Issue. This bash app will sync the time of WSL & Windows after computer goes to sleep using two approaches: hwclock & wsl --shutdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# -------------------- A temporary-manual-notgreat fix for the time syncing problem between Windows & WSL -------------------- | |
# -------------------- Please read the code & commented sections before execution -------------------- | |
# Not removing the trailing \r from the PowerShell, results in NotSynced even if time is Synced | |
WinTime=$(powershell.exe "& {get-date -UFormat '%Y/%m/%d %H:%M:%S'}" | tr -d '\r') | |
WSLTime=$(date +"%Y/%m/%d %H:%M:%S") | |
RED="\033[0;31m" | |
GREEN="\033[0;32m" | |
# No Color | |
NC="\033[0m" | |
if [ "$WinTime" != "$WSLTime" ]; then | |
echo "🪟 Windows: $WinTime" | |
echo "🐧 WSL: $WSLTime" | |
echo "❌ NotSynced" | |
# Format strings to make the command's color red | |
printf "Trying to sync the time using$RED sudo hwclock -s$NC\n" | |
# Take the user's password without showing it (-s) | |
read -s -p "Please enter your root password:" -r PassWord | |
# echo the given PassWord to the sudo command | |
echo "$PassWord" | sudo -S hwclock -s | |
echo "" | |
# Re-run check | |
NewWinTime=$(powershell.exe "& {get-date -UFormat '%Y/%m/%d %H:%M:%S'}" | tr -d '\r') | |
NewWSLTime=$(date +"%Y/%m/%d %H:%M:%S") | |
echo "🪟 Windows: $NewWinTime" | |
echo "🐧 WSL: $NewWSLTime" | |
printf "$RED Note that if you have 1 second delay, it's probably fixed (you can try the command$GREEN date$NC$RED), the delay is because of the execution, so please send$GREEN n$NC$RED on next question$NC\n" | |
if [ "$NewWinTime" != "$NewWSLTime" ]; then | |
while true; do | |
echo "" | |
read -p "Time not synced yet! Would you like to restart the WSL? (y/n)" -r RSWSL | |
case $RSWSL in | |
[Yy]* ) | |
# Before Restarting WSL, save your work on opened WSL! (VSCode) | |
# This will be activate the default Ubuntu | |
wsl.exe --shutdown && wsl.exe -d Ubuntu;; | |
[Nn]* ) | |
exit;; | |
* ) | |
echo "Please answer y or n.";; | |
esac | |
done | |
# Re-run check & show the final result | |
FinalWinTime=$(powershell.exe "& {get-date -UFormat '%Y/%m/%d %H:%M:%S'}") | |
FinalWSLTime=$(date +"%Y/%m/%d %H:%M:%S") | |
echo "🪟 Windows: $FinalWinTime" | |
echo "🐧 WSL: $FinalWSLTime" | |
fi | |
else | |
echo "✅ Synced" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cd ~
).~./FixWSLTime.sh