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:
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: &, jobs, fg, bg, disown, nohup
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 &
disown
or just use nohup from the start if you know you want that:
nohup ./server.sh > out.log 2>&1 &
subshells — cd somewhere temporarily with ( )
wrap stuff in () and it runs in its own little world:
(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:
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)
one-liners: waiting on a port, polling, parallel xargs
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; done
parallel stuff with xargs:
find . -name "*.png" | xargs -P4 -I{} convert {} {}.webp
see 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