File: lang-bash.md

package info (click to toggle)
rust-wasmtime 26.0.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 48,504 kB
  • sloc: ansic: 4,003; sh: 561; javascript: 542; cpp: 254; asm: 175; ml: 96; makefile: 55
file content (42 lines) | stat: -rw-r--r-- 819 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Using WebAssembly from Bash

## Getting started and simple example

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

```text
$ 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`

```wat
{{#include ../examples/gcd.wat}}
```

Create a bash script that will invoke GCD three times.

## `gcd.sh`

```bash
#!/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
```