Last Updated: February 25, 2016
·
1.614K
· byvoid

Batsh - A language that compiles to Bash and Windows Batch

Batsh is a simple C-based programming language that compiles to Bash, Windows Batch. It enables you to write code once runs on all platforms without any additional dependency.

Both Bash and Batch are messy to read and tricky to write due to historical reasons. You have to spend a lot of time learning either of them, and write platform-dependent code for each operating system. If you happen to be a maintainer of a cross-platform tool which relies on Bash on Linux/Mac and Batch on Windows as "glue code", and found it painful to "synchronize" between them, you would like to try Batsh.

Online demo: http://batsh.byvoid.com/

Project: https://github.com/BYVoid/Batsh

Example:

function fibonacci(num) {
  if (num == 0) {
    return 0;
  } else if (num == 1) {
    return 1;
  } else {
    return (fibonacci(num - 2) + fibonacci(num - 1));
  }
}
println(fibonacci(8));

Compiled code (Bash):

function fibonacci {
  local _1
  local num
  local _0
  num=$1
  if [ $num == $((0)) ]; then
    "echo" "-ne" $((0))
    return
  else
    if [ $num == $((1)) ]; then
      "echo" "-ne" $((1))
      return
    else
      _0=$("fibonacci" $(($num - 2)))
      _1=$("fibonacci" $(($num - 1)))
      "echo" "-ne" $(($_0 + $_1))
      return
    fi
  fi
}
"echo" "-e" $("fibonacci" $((8)))

Compiled code (Windows Batch):

@echo off
setlocal EnableDelayedExpansion
setlocal EnableExtensions

call :fibonacci _1 0 8
set _0=!_1!
echo !_0!

goto :EOF
:fibonacci
set num_%~2=%~3
if /i !num_%~2! EQU 0 (
  set %~1=0
  goto :EOF
) else (
  if /i !num_%~2! EQU 1 (
    set %~1=1
    goto :EOF
  ) else (
    set /a _0_%~2=^(!num_%~2! - 2^)
    set /a _5_%~2=^(1 + %~2^)
    call :fibonacci _6_%~2 !_5_%~2! !_0_%~2!
    set _1_%~2=!_6_%~2!
    set /a _2_%~2=^(!num_%~2! - 1^)
    set /a _7_%~2=^(1 + %~2^)
    call :fibonacci _8_%~2 !_7_%~2! !_2_%~2!
    set _3_%~2=!_8_%~2!
    set /a _4_%~2=^(!_1_%~2! + !_3_%~2!^)
    set %~1=!_4_%~2!
    goto :EOF
  )
)