> For the complete documentation index, see [llms.txt](https://documentation.hak5.org/packet-squirrel-mark-ii/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://documentation.hak5.org/packet-squirrel-mark-ii/advanced-payloads/background-commands.md).

# Background commands

## Running commands in the background

Normally, commands in a payload are run until they complete, then the next command runs.  This blocks the rest of the payload from executing while a long-running command runs.

Often this is desirable:  This functionality is what allows a payload to pause until a button is pressed, for instance.

At other times, a payload may need a command to run in the background; to run multiple `KILLSTREAM` commands with different patterns, monitor status of a command, or for other reasons.

To solve this, commands can be run concurrently, called "backgrounding".  Any number of commands or functions can be run in the background at once; when backgrounded, the payload immediately executes the next command.

Appending an `&` to the end of a command tells Bash to run this command in the background.

To run multiple commands, simply run all of them with an `&` after each:

```bash
#!/bin/bash 

# Title: Killstream multi example
#
# Description: Kill multiple types of streams

NETMODE BRIDGE
LED R SINGLE


KILLSTREAM br-lan ANY 'Authorization: Basic' 80 &
KILLSTREAM br-lan ANY 'Foobar' 80 &
KILLSTREAM br-lan ANY '[0-9}{3}-[0-9]{2}-[0-9]{4}' 80 &

wait
```

All the commands will be run, regardless if the commands are successful.

### Waiting for commands

In the example above, the `wait` command is used.  This keeps the payload running until all backgrounded commands have finished.

Without the `wait` command, the payload above would run the `KILLSTREAM` command, but then immediately complete:  Backgrounded commands will not keep a payload running!

Using the `wait` command tells the payload to continue running.  In this case, it will run indefinitely, as the `KILLSTREAM` command runs forever.

## Running groups of commands in the background

A group of commands can be made using the `{` and `}` symbols, and run in the background.

This can easily be combined with the `while true` loop to run forever, and something like the `BUTTON` command to wait for user input, for example:

```bash
#!/bin/bash

# Title: Button blinky
# 
# Description: Blink the LED whenever the button is pressed

NETMODE NAT

# Group the commands inside {} and run them in the background with &
{
    # Repeat forever
    while true; do
        # Wait for the button
        BUTTON
        
        # Set the LED to blue
        LED B SOLID
        
        # Wait a second
        sleep 1
    done
} &

# Do whatever else in the payload here

wait
```
