Run Shell Scripts in Windows OS

Photo by Andrew Neel on Unsplash

Run Shell Scripts in Windows OS

Associate cygwin's bash as default program to run shell scripts

What is Cygwin?

Cygwin is a collection of open source tools that allows source code designed for Unix-like operating systems to compile and execute in Windows OS. We will be using cygwin which contains bash command language interpreter required to run shell scripts. You can download cygwin installer from this link. You can follow steps mentioned in this video to install it.

assoc command

assoc is command used for display or modify file extension association in windows OS.

  • Syntax: assoc <.[extension]>=<filetype>
  • To view required file type association: assoc <.[extension]>
  • To associate a file type for example .log file with text file: assoc .log=txtfile
  • Remove file association for file extension: assoc <.[extension]>=

Please follow official documentation to know more about it.

Note: This command is only supported within cmd.exe and is not available in PowerShell. User requires admin privilege to run this command.

ftype command

fype command displays or modifies file types that are used in file name extension associations.

  • Syntax: ftype <filetype>=<open command string>
  • To display command string for txtfile file type: ftype txtfile
  • Delete open command string for a file type: ftype <filetype>=

Please follow official documentation to know more about it.

Note: User requires admin privilege to run this commad.

Steps to associate cygwin's bash with .sh file extension

  1. Save below code in a batch file (say setShellDefault.bat). Please replace PATH_TO_BASH_EXE with absolute path to bash.exe in your local system (C:\cygwin64\bin\bash.exe or C:\cygwin\bin\bash.exe).
    assoc .sh=bashscript
    ftype bashscript="PATH_TO_BASH_EXE" -li '%%1' '%%*'
    
  2. Right click on this batch file and select Run as administrator.

Now, any file with extension .sh will run using bash.

Steps to remove bash as default program to run shell script

If you want to undo previous steps which will remove bash as default program to run shell script

  1. Open command prompt as admin
  2. Run below two commands in command prompt one by one
    assoc .sh=
    ftype bashscript=
    
    Note: The steps are tested in Windows 10 OS. You may find error "bash: $'\r': command not found". This is due to windows style newline character. Please change settings in your text editor to make it unix style newline character.