Process Tricks
how to chain commands, run stuff in the background, and generally control what’s happening in your terminal.
chaining
&& — only run the next thing if the first one worked:
make && make install
cd /project && npm start|| — only run the next thing if the first one FAILED:
cd /mydir || mkdir /mydir
ping -c1 server.com || echo "it's down"combine them for a ghetto ternary:
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:
echo "start"; sleep 2; echo "done"background jobs
stick & at the end:
./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), 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:
./server.sh &
disownor just use nohup from the start if you know you want that:
nohup ./server.sh > out.log 2>&1 &subshells
wrap stuff in () and it runs in its own little world:
(cd /tmp && tar xf thing.tar.gz)
# still in your original directory after thisI use this a lot when I need to cd somewhere temporarily. no cleanup needed.
process substitution
this is a sleeper feature. <() lets you use command output as if it were a file:
diff <(sort file1.txt) <(sort file2.txt)no temp files. works great for comparing remote stuff too:
diff <(ssh server1 cat /etc/config) <(ssh server2 cat /etc/config)a few one-liners I keep coming back to
wait for a port:
while ! nc -z localhost 8080; do sleep 1; done; echo "ready"poor man’s watch:
while true; do clear; date; curl -s localhost/health; sleep 5; doneparallel stuff with xargs:
find . -name "*.png" | xargs -P4 -I{} convert {} {}.webpsee also: bash-keyboard-shortcuts, bash-quick-loops, bash-history-expansion
greg’s wiki on job control — greg’s wiki is honestly one of the best bash resources out there