# Bash Process Tricks

chaining commands with `&&` and `||`, backgrounding and disowning jobs, subshells, and process substitution with `<()` — how to control what's actually happening in your terminal.

## chaining commands with &&, || and ;

`&&` — only run the next thing if the first one worked:

```bash
make && make install
cd /project && npm start
```

`||` — only run the next thing if the first one FAILED:

```bash
cd /mydir || mkdir /mydir
ping -c1 server.com || echo "it's down"
```

combine them for a ghetto ternary:

```bash
test -f config.yml && echo "found it" || echo "nope"
```

not technically a real ternary (the `||` fires if the `echo` fails too, which it won't, but still). good enough for quick checks.

`;` just runs stuff in order no matter what:

```bash
echo "start"; sleep 2; echo "done"
```

## background jobs: &, jobs, fg, bg, disown, nohup

stick `&` at the end:

```bash
./slow-thing.sh &
```

your terminal is free. `jobs` to see what's running, `fg` to bring it back.

if you accidentally started something without `&`, hit `Ctrl+Z` to suspend it ([Bash Keyboard Shortcuts](/articles/bash-keyboard-shortcuts)), then `bg` to let it keep running in the background.

`disown` detaches it from your terminal completely — so it survives after you close the tab:

```bash
./server.sh &
disown
```

or just use `nohup` from the start if you know you want that:

```bash
nohup ./server.sh > out.log 2>&1 &
```

## subshells — cd somewhere temporarily with ( )

wrap stuff in `()` and it runs in its own little world:

```bash
(cd /tmp && tar xf thing.tar.gz)
# still in your original directory after this
```

I use this a lot when I need to cd somewhere temporarily. no cleanup needed.

## process substitution — diff <(cmd) without temp files

this is a sleeper feature. `<()` lets you use command output as if it were a file:

```bash
diff <(sort file1.txt) <(sort file2.txt)
```

no temp files. works great for comparing remote stuff too:

```bash
diff <(ssh server1 cat /etc/config) <(ssh server2 cat /etc/config)
```

## one-liners: waiting on a port, polling, parallel xargs

wait for a port:

```bash
while ! nc -z localhost 8080; do sleep 1; done; echo "ready"
```

poor man's watch:

```bash
while true; do clear; date; curl -s localhost/health; sleep 5; done
```

parallel stuff with xargs:

```bash
find . -name "*.png" | xargs -P4 -I{} convert {} {}.webp
```

---

see also: [Bash Keyboard Shortcuts](/articles/bash-keyboard-shortcuts), [Bash Quick Loops](/articles/bash-quick-loops), [Bash History Expansion](/articles/bash-history-expansion)

[greg's wiki on job control](https://mywiki.wooledge.org/BashGuide/JobControl) — greg's wiki is honestly one of the best bash resources out there
