Execute bash scripts on cygwin directly via Windows interface

Submitted by-badmin- onjeu 21/04/2016 - 14:53

After reading the excellent article about cygwin bash scripts under Windows by duncansmart, I wanted to adapt this script so it could handle scheduled tasks as system without having a windows user account involved (launching bash without --login option).

So, in order to execute a bash script called something.sh in /cygdrive/c/home/something.sh, here is the counterpart that will execute the script directly from Windows, called c:\cygwin\home\something.cmd:

@echo off
setlocal

:: Check if a bash script exists with the same name as the windows script
if not exist "%~dpn0.sh" echo Script "%~dpn0.sh" not found & exit 2

:: Check if cygwin is in _CYGBIN dir
set _CYGBIN=C:\cygwin\bin
if not exist "%_CYGBIN%" echo Couldn't find Cygwin at "%_CYGBIN%" & exit 3

:: Add cygwin path variable before windows path so gnu utils (like find or ping) will be used before their windows counterparts
:: Also usefull when not logging in as a user with bash
set PATH=/usr/bin;/usr/local/bin;%PATH%

:: Resolve ___.sh to /cygdrive based *nix path and store in %_CYGSCRIPT%
for /f "delims=" %%A in ('%_CYGBIN%\cygpath.exe "%~dpn0.sh"') do set _CYGSCRIPT=%%A

:: Throw away temporary env vars and invoke script, passing any args that were passed to us
%_CYGBIN%\bash "%_CYGSCRIPT%" %*
endlocal