/
Running terminal commands

Running terminal commands

The terminal provides command-line access to your computer, enabling you to run shell commands, execute scripts, and interact with system utilities. In this guide, we'll walk through how to use the terminal to run commands in the foreground and background (for long-running processes).


Run terminal commands

You can run commands using the terminal.run method.

import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Run terminal command
const result = await computer.terminal.run("ls -l");
console.log(result);
// Stop computer
await computer.stop();

Stream terminal output

To stream command output as it is being executed, pass the onData and onError callbacks to the terminal.run() method in JavaScript or the on_data and on_error callbacks to the commands.run() method in Python.

import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Run terminal command
await computer.terminal.run("echo hello; sleep 10; echo world", {
onData: (data) => {
console.log(data);
},
onError: (error) => {
console.error(error);
}
});
// Stop computer
await computer.stop();

Run commands in the background

You can run commands in the background using the background option. When running a command in the background, it returns a handle that you can use to wait for the command to finish or kill the command.

import { Computer } from "@metallichq/sdk";
// Start computer
const computer = await Computer.start("your-computer-id");
await computer.waitForState("started");
// Run terminal command
const handle = await computer.terminal.run("echo hello; sleep 10; echo world", {
background: true
});
// Wait for the command to finish
const result = await handle.wait();
console.log(result);
// Kill the command
await handle.kill();
// Stop computer
await computer.stop();