Using WebAssembly from Bash

Getting started and simple example

First up you'll want to start a new module:

$ mkdir -p gcd-bash
$ cd gcd-bash
$ touch gcd.wat gcd.sh

Next, copy this example WebAssembly text module into your project. It exports a function for calculating the greatest common denominator of two numbers.

gcd.wat

(module
  (func $gcd (param i32 i32) (result i32)
    (local i32)
    block  ;; label = @1
      block  ;; label = @2
        local.get 0
        br_if 0 (;@2;)
        local.get 1
        local.set 2
        br 1 (;@1;)
      end
      loop  ;; label = @2
        local.get 1
        local.get 0
        local.tee 2
        i32.rem_u
        local.set 0
        local.get 2
        local.set 1
        local.get 0
        br_if 0 (;@2;)
      end
    end
    local.get 2
  )
  (export "gcd" (func $gcd))
)

Create a bash script that will invoke GCD three times.

gcd.sh

#!/bin/bash

function gcd() {
  # Cast to number; default = 0
  local x=$(($1))
  local y=$(($2))
  # Invoke GCD from module; suppress stderr
  local result=$(wasmtime --invoke gcd examples/gcd.wat $x $y 2>/dev/null)
  echo "$result"
}

# main
for num in "27 6" "6 27" "42 12"; do
  set -- $num
  echo "gcd($1, $2) = $(gcd "$1" "$2")"
done