simple_macros.md (960B)
1 <!-- :Tangle(sh) DIRNAME/FILENAME.sh --> 2 # Simple macros 3 Testing simple macro tangling. 4 5 <!-- :Tangle(sh) <^> --> 6 ```sh 7 #!/bin/sh 8 <<mktemp and trap>> 9 10 <<define functions>> 11 12 <<main>> 13 14 <<untrap>> 15 ``` 16 17 We will work in a temporary directory: 18 19 <!-- :Tangle(sh) <mktemp and trap> --> 20 ```sh 21 tempdir="$(mktemp -d)" 22 trap 'rm -r $tempdir' INT TERM EXIT 23 ``` 24 25 We want to also cancel the trap once we're ready to exit normally: 26 27 <!-- :Tangle(sh) <untrap> --> 28 ```sh 29 rm -r "$tempdir" 30 trap - INT TERM EXIT 31 ``` 32 33 Now to define some functions. 34 First, a greeter: 35 36 <!-- :Tangle(sh) <define functions> --> 37 ```sh 38 # args: name 39 greeter() { 40 printf "Hello, %s!\n" "$1" 41 } 42 ``` 43 44 And an adder (wow I'm so creative): 45 46 <!-- :Tangle(sh) <define functions>+ --> 47 ```sh 48 # args: numbers a,b to add 49 adder() { 50 a="$1" 51 b="$2" 52 echo $((a+b)) > "$tempdir"/the_answer 53 } 54 ``` 55 56 Then we'll do some work and actually call the functions. 57 58 <!-- :Tangle(sh) <main> --> 59 ```sh 60 greeter there 61 adder 23 19 62 ```