aboutsummaryrefslogtreecommitdiff
path: root/docs/shell.md
blob: f453a1d0b57573dc5d1cfa6fcc5726fc328d0824 (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# Shell Scripting

Tomo comes with a built-in [lang](langs.md) called `Shell` for shell commands.
This lets you write and invoke shell commands in a more type-safe way.

```tomo
user_name := ask("What's your name? ")
_ := $Shell"echo Hello $user_name"
```

In the above example, there is no risk of code injection, because the
user-controlled string is automatically escaped when performing interpolation.

## Shell Methods

### `by_line`

**Description:**  
Run a shell command and return an iterator over its output, line-by-line.

**Signature:**  
```tomo
func by_line(command: Shell -> Void)
```

**Parameters:**

- `command`: The command to run.

**Returns:**  
An optional iterator over the lines of the command's output. If the command fails
to run, `none` will be returned.

**Example:**  
```tomo
i := 1
for line in $Shell"ping www.example.com":by_line()!:
    stop if i > 5
    i += 1
```

### `execute`

**Description:**  
Execute a shell command without capturing its output and return its exit status.

**Signature:**  
```tomo
func execute(command: Shell -> Int32?)
```

**Parameters:**

- `command`: The command to execute.

**Returns:**  
If the command exits normally, return its exit status. Otherwise return `none`.

**Example:**  
```tomo
>> $Shell"touch file.txt":execute()
= 0?
```

---

### `run`

**Description:**  
Run a shell command and return the output text from `stdout`.

**Signature:**  
```tomo
func run(command: Shell -> Text?)
```

**Parameters:**

- `command`: The command to run.

**Returns:**  
If the program fails to run (e.g. a non-existent command), return `none`,
otherwise return the entire standard output of the command as text. **Note:**
if there is a trailing newline, it will be stripped.

**Example:**  
```tomo
>> $Shell"seq 5":run()
= "1$\n2$\n3$\n4$\n5"
```

---

### `run_bytes`

**Description:**  
Run a shell command and return the output in raw bytes from `stdout`.

**Signature:**  
```tomo
func run(command: Shell -> [Byte]?)
```

**Parameters:**

- `command`: The command to run.

**Returns:**  
If the program fails to run (e.g. a non-existent command), return `none`,
otherwise return the entire standard output of the command as an array of
bytes.

**Example:**  
```tomo
>> $Shell"seq 5":run_bytes()
= [0x31, 0x0A, 0x32, 0x0A, 0x33, 0x0A, 0x34, 0x0A, 0x35, 0x0A]
```