Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hktonylee/071134e8873382c1645fa45de53abc8c to your computer and use it in GitHub Desktop.
Save hktonylee/071134e8873382c1645fa45de53abc8c to your computer and use it in GitHub Desktop.
How to auto-start WSL during Windows startup, and run services (e.g. cron) in WSL2?
  1. Ran sudo visudo. Add this line:

    ALL ALL= NOPASSWD: /usr/local/etc/start_services.sh
    
  2. Create file /usr/local/etc/start_services.sh

    touch /usr/local/etc/start_services.sh
    chmod go-rwx /usr/local/etc/start_services.sh
    chown root:root /usr/local/etc/start_services.sh
    
  3. In the file, run the services needed:

    #!/usr/bin/env sh
    
    service cron start
  4. In ~/.zprofile (or other profile scripts of your favourite shell). Add these lines:

    service cron status >/dev/null 2>&1 || {
      echo 'Services have not started. Starting services now'
      sudo /usr/local/etc/start_services.sh
    }
    
  5. Press Window+R, run shell:startup

  6. Create a file named start-wsl.cmd. Add these lines:

    @echo off
    
    echo Starting WSL...
    wsl -e echo "WSL Started"
    
    echo Starting services...
    C:\Windows\System32\bash.exe -c "sudo /usr/local/etc/start_services.sh"
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment