Friday, May 26, 2017

Install Cygwin in a script

I built an Intellij docker image based on CentOS 7. To allow my colleagues to use it on Windows, I need to help them to setup a X window system. This post describe how to setup Cygwin/X using a script without user intervention.
To run in Windows, the best choice for the script is PowerShell. PowerShell is powerful, but ugly compared to Bash.
$CygwinDir=<where you want to install Cygwin>
$CygwinPkgsDir=<where the cygwin packages are cached>

function Download($uri, $outfile) {
  $webClient = New-Object System.Net.WebClient
  $Webclient.DownloadFile($uri, $outfile)
}

function Install-CygwinX {
  $setup = "$DownloadDir\setup-x86_64.exe"
  if (!(Test-Path "$setup")) {
    Download `
      -uri "https://cygwin.com/setup-x86_64.exe" `
      -outfile "$setup"
  }

  Start-Process "$setup" -ArgumentList "--site ""http://mirrors.xmission.com/cygwin"" --root ""$CygwinDir"" --packages xorg-server,xhost --no-admin --local-package-dir ""$CygwinPkgsDir"" --upgrade-also --quiet-mode" -Wait -NoNewWindow
}
You can run this command to get the full list of command line options:
Downloads\setup-x86_64.exe --help
Most important command line options of Cygwin setup are:
  • --no-admin: Your user won’t have to be administrator
  • --quiet-mode: The script will run without asking anything
  • --packages: the packages you need to run a Cygwin/X. No package selection is needed.
The PowerShell script will download the setup executable and run it automatically. Here are some thing you need to know:
  • Don’t use Invoke-WebRequest because it is too slow. For Cygwin setup, it is not a big problem because setup-x86_64.exe is small, and Cygwin setup will download the rest package. If you download about 200MB file like ‘Docker Toolbox for Windows’, you will see how slow it is.
  • Use Start-Process to start the setup executable.
    • -Wait makes the script wait until Cygwin setup finished
    • -NoNewWindow is important if you run a .bat file. Without it, your .bat file will run in a separate window, just appear then disappear. If anything is wrong, you have no way to see what is the error message.

No comments:

Post a Comment