All tags
Start here · scriptingAdvanced tmux, a config that grows with you, formats, layouts and more9 steps · 52 min read · People who know the tmux basicsStart the guide scripting
Narrow down
Guides1
Shell60
- Tip
echo $EPOCHSECONDS$EPOCHSECONDS and $EPOCHREALTIME give you the time without calling dateTwo bash variables hold the current Unix time in seconds, or with microseconds.3 Dec 2026 - Tip
sudo smartctl -q silent -a /dev/sdaSmartctl returns a bitmask, so a script can read smart trouble from $?Decodes the smartctl exit status so your script knows what went wrong.1 Dec 2026 - Tip
APP_HOST=example.com${!PREFIX@} lists every bash variable whose name starts the sameLoop over all settings like APP_PORT and APP_HOST without naming each one.30 Nov 2026 - Tip
set -eShopt -s inherit_errexit makes set -e work inside $( ) in bashStop a command substitution at the first failing line, like the rest of the script.30 Nov 2026 - Tip
cd /srv/app/releases || exit 1cd folder || exit stops a shell script that ends up in the wrong placeMake a script quit when cd fails, before it runs commands in the wrong folder.30 Nov 2026 - Tip
printf '\033]0;%s\007' "deploy running"One printf line sets the title of your terminal tabNames a terminal tab or window from the command line or from a script.30 Nov 2026 - Tip
make 2>&1 | tmux split-window -IPiping into tmux split-window -I shows output in a new paneSends a command's output from a script into a fresh pane.30 Nov 2026 - Tip
source s.sh; echo "$PWD $X" # /tmp 1source runs a file in your current shell, ./script in a new oneKnow why cd and variables from a script vanish, and when source keeps them.30 Nov 2026 - Tip
a=(a b c d e)${arr[@]:1:2} takes a slice out of a bash arrayGet some elements of an array, like all but the first, without a loop.30 Nov 2026 - Tip
tmux has-session -t "$S" 2>/dev/null && exec tmux attach -t "$S"A small shell script builds your tmux session with all windowsRecreates the same windows, panes and commands with one command.30 Nov 2026 - Tip
files=("my file.txt" notes.md)Quote "${files[@]}" so bash keeps names with spaces in one pieceExpand an array without breaking elements that contain spaces.30 Nov 2026 - Tip
exec > >(tee -a /var/log/nightly.log) 2>&1exec with tee logs everything a shell script printsSend all output of a script to a log file while you still see it on screen.30 Nov 2026 - Tip
red=$(tput setaf 1); green=$(tput setaf 2)Tput setaf colours script output in the terminal without hard coded escapesAdds colour to script messages in a way that stays quiet on dumb terminals.30 Nov 2026 - Tip
sleep $((RANDOM % 300))sleep $((RANDOM % 300)) spreads shell cron jobs over a few minutesAdd a random delay so many machines do not hit the same server at once.30 Nov 2026 - Tip
echo ./*./* protects shell commands from file names that start with a dashStop a file called -rf from being read as an option by rm or mv.30 Nov 2026 - Tip
journalctl -t demoapp -n 1 -o json-seq | od -c | head -1journalctl -o json-seq writes records that survive a cut off streamGet JSON records with a clear start marker, so a half written line can be skipped.30 Nov 2026 - Tip
set -xBASH_XTRACEFD sends set -x output of a bash script to its own fileKeep trace lines out of the normal error output of a script.30 Nov 2026 - Tip
osascript -e 'display notification "Backup finished" with title "Terminal" sound name "Glass"'osascript display notification tells you when a terminal job is doneShows a macOS notification from a script or after a long command.30 Nov 2026 - Tip
bash -c 'exit -1'; echo $? # 255A shell exit code only goes up to 255, so exit 256 means successKeep exit codes between 0 and 255, because larger numbers wrap around.30 Nov 2026 - Tip
[[ -v b ]] && echo set || echo unset # set[[ -v name ]] tells bash whether a variable is set at allTell an unset variable apart from one that is set to an empty string.30 Nov 2026 - Tip
hosts=(web db cache)${!arr[@]} lists the indexes of a bash array, gaps and allLoop over positions or keys of an array, also after removing elements.30 Nov 2026 - Tip
systemd-detect-virtsystemd-detect-virt tells a script whether it runs in a VM or containerLet a script check if it is on bare metal, in a VM or inside a container.30 Nov 2026 - Tip
declare -f mkcddeclare -f prints the code of a shell function you loaded earlierSee what a function in your shell really does, and where it came from.30 Nov 2026 - Tip
wait "$db_pid"; db_status=$?wait PID gives you the exit code of one bash background jobRun jobs in parallel and still check which of them failed.30 Nov 2026 - Tip
EOFA quoted EOF stops the shell from expanding a here-documentWrite a script or config with dollar signs from a here-document, untouched.30 Nov 2026 - Tip
set -e((i++)) stops a bash script under set -e when i is 0Avoid a counter that silently ends your script on its first increment.30 Nov 2026 - Tip
echo '203.0.113.10 nas.example.com' | sudo tee -a /etc/hosts >/dev/nullSudo tee writes to a root-owned file where a shell redirect failsAppend a line to a file owned by root, because sudo echo > file fails.30 Nov 2026 - Tip
envsubst < site.conf.tpl > site.confenvsubst fills shell variables into a template fileTurn a config template with $VARIABLES into a real file without sed.30 Nov 2026 - Tip
key='abc123xyz'${#var} gives the length of a bash string or arrayCount characters or array items without wc or a loop.30 Nov 2026 - Tip
[Service]ExecCondition= lets a script decide whether a systemd service runsSkip a service quietly when a check command says now is not the time.30 Nov 2026 - Tip
echo "needs bash 4 or newer, this is $BASH_VERSION" >&2BASH_VERSINFO stops a script that needs a newer bash than macOS shipsFail early with a clear message when bash is too old for your script.30 Nov 2026 - Tip
select action in start stop status quit; doselect gives a bash script a numbered menu in a few linesLet a user pick an option by number without writing your own menu loop.30 Nov 2026 - Tip
compgen -c | sort -u | grep '^systemd-'compgen -c lists every command bash can run right nowSearch all commands, aliases and functions your bash knows about.30 Nov 2026 - Tip
echo "main: $$ $BASHPID"$BASHPID gives the real PID in bash where $$ shows the parentGet the PID of the current subshell, where $$ still shows the parent.30 Nov 2026 - Tip
die() { echo "error: $*" >&2; stack >&2; exit 1; }FUNCNAME and BASH_LINENO print a stack trace from a bash scriptShow which chain of function calls led to an error in a longer script.30 Nov 2026 - Tip
bash -n backup.sh && echo "syntax ok"bash -n checks a script for syntax errors without running itParses a script and reports syntax errors without executing a single command.28 Nov 2026 - Tip
shopt -s lastpipeshopt -s lastpipe keeps variables set inside a piped while loopRuns the last command of a pipeline in the current shell so its variables survive.28 Nov 2026 - Tip
source "$script_dir/config.env"BASH_SOURCE finds the folder a script lives inFinds the directory of the running script so it can load files next to it.28 Nov 2026 - Tip
printf -v stamp '%(%Y-%m-%d_%H%M)T' -1printf %(…)T puts today's date in a name without calling dateWrites the current date into a shell variable using only the printf builtin.28 Nov 2026 - Tip
read -r -s -p "Token: " token; echoread -s -p hides what you type, and -t gives up after a timeoutPrompts for input without echoing it and gives up after a set number of seconds.28 Nov 2026 - Tip
printf '%s\n' "holiday photo.jpg" "notes 2026.txt" | xargs -d '\n' -n1 echoXargs -d '\n' keeps file names with spaces in one pieceMakes xargs split its input only at newlines, so names with spaces stay whole.28 Nov 2026 - Tip
false | true | falseBash PIPESTATUS shows which part of a pipeline failedReads the exit code of every command in the last pipeline, not only the final one.28 Nov 2026 - Tip
set -uset -u makes a script stop on a typo in a variable nameMakes bash exit with an error instead of treating an unset variable as empty.28 Nov 2026 - Tip
ssh -o BatchMode=yes -o ConnectTimeout=5 [email protected] uptimessh -o BatchMode=yes makes scripts fail instead of waiting for a passwordStops ssh from asking for passwords or confirmations, so a script fails fast instead of hanging.28 Nov 2026 - Tip
tmux list-panes -a -F '#{session_name}:#{window_index}.#{pane_index} #{pane_current_command} #{pane_current_path}'tmux list-panes -a -F lists every pane on the server with its folder and commandPrints one line per pane on the whole tmux server, in a format you choose.28 Nov 2026 - Tip
journalctl -u nginx.service --cursor-file=/var/tmp/nginx.cursorjournalctl --cursor-file continues where the last run stoppedStores the position of the last log entry in a file so the next journalctl run only shows new lines.28 Nov 2026 - Tip
local -n _list=$1local -n lets a bash function change an array you pass by namePasses an array to a bash function by name, so the function can change the original.27 Nov 2026 - Tip
declare -p appsdeclare -p shows exactly what is inside a bash variable or arrayPrints the type and exact quoted value of a bash variable, array or function.27 Nov 2026 - Tip
count=10Local keeps a bash function from overwriting your variablesKeeps the variables of a bash function inside that function, so callers keep their values.27 Nov 2026 - Tip
f="my holiday photo.jpg"${var//old/new} replaces every match inside a bash variableSwaps text inside a bash variable, once or everywhere, without calling sed.27 Nov 2026 - Tip
SECONDS=0The SECONDS variable tells a bash script how long it has been runningTimes a script or one step of it in bash without calling date.27 Nov 2026 - Tip
for f in *.log; doShopt -s nullglob stops a for loop from running on a literal *.logMakes a bash glob that matches no files disappear, so loops skip instead of failing.27 Nov 2026 - Tip
set -xset -x with a better PS4 shows the line number of every traced commandShows the file and line number in front of every command bash traces with set -x.27 Nov 2026 - Tip
systemctl show nginx.service -p MainPID --valuesystemctl show --value prints one clean systemd property for scriptsPrints a single unit property without labels, so scripts can read it directly.24 Nov 2026 - Tip
trap 'rm -rf "$tmp"' EXITtrap EXIT cleans up your temp files, even when the script diesRuns a cleanup command whenever the script exits, including after an error.4 Jul 2026 - Tip
rm -rf "${BUILD_DIR:?BUILD_DIR is not set}"/*${var:?} stops a script before an empty variable eats your filesStops the script with an error when a variable is empty, before a delete can hit the wrong path.24 Jun 2026 - Tip
set -o pipefailset -o pipefail makes a pipeline fail when any part of it failsMakes a pipeline report failure when any command in it fails, not only the last one.18 Jun 2026 - Tip
printf '%s\n' alpha beta gamma | paste -sd, -Paste -sd, joins lines into one comma separated terminal lineJoins every input line into one line with a chosen separator.21 Apr 2026 - Tip
comm -23 <(sort old.txt) <(sort new.txt)comm -23 lists lines only in one file, a terminal set differencePrints the lines that exist in the first sorted file but not in the second.21 Apr 2026 - Tip
read -r rows cols <<< "$(stty size)"Stty size gives scripts the rows and columns of your terminalPrints the number of rows and columns of the current terminal window.20 Apr 2026
Python33
- Tip
import asyncioPython's asyncio.timeout puts a time limit on a block of awaitsWrap awaits in asyncio.timeout and get a TimeoutError when the time is up.2 Dec 2026 - Tip
from itertools import accumulatePython's itertools.accumulate gives a running total of a listaccumulate yields the running sum, or a running max or product if you pass a function.2 Dec 2026 - Tip
match cmd.split():Python's match statement picks apart lists and values by their shapematch and case unpack sequences by shape, with guards and alternatives, from Python 3.10.2 Dec 2026 - Tip
from pathlib import PathPython's Path.read_text and write_text replace the open and with boilerplateRead or write a whole small file in one line with pathlib.30 Nov 2026 - Tip
from concurrent.futures import ThreadPoolExecutorPython's ThreadPoolExecutor.map runs slow network calls side by sideSpeed up a script that waits on many downloads or API calls with a thread pool.30 Nov 2026 - Tip
import hashlibPython's hashlib.file_digest checksums a file without a read loopCompute a SHA256 checksum of a file in one call, even for big files.30 Nov 2026 - Tip
sys.exit("activate the virtual environment first (source .venv/bin/activate)")Python's sys.prefix tells a script whether it runs in a virtual environmentMake a script check that it's running inside a venv before it installs or changes things.30 Nov 2026 - Tip
msg += f", did you mean {hint[0]!r}?"Python's difflib.get_close_matches adds a did you mean to your scriptSuggest the closest valid option when someone mistypes a command or name.30 Nov 2026 - Tip
import difflibDifflib.unified_diff shows what a script changed in a config filePrint a diff of two texts from a script, in the same format as git and diff -u.30 Nov 2026 - Tip
import tempfile, shutilPython's tempfile.TemporaryDirectory cleans up after itselfGet a scratch folder that disappears on its own when your code is done with it.30 Nov 2026 - Tip
import secretsPython's secrets module makes tokens that are safe to use as passwordsGenerate random tokens for API keys and passwords with the right kind of randomness.30 Nov 2026 - Tip
import shlexPython's shlex.split and shlex.quote handle shell quoting for youSplit a command line like the shell does, and quote values safely for one.30 Nov 2026 - Tip
import subprocessPython's subprocess.run with check=True stops on a failed commandRun a shell command from Python, capture its output and fail loudly on errors.30 Nov 2026 - Tip
from collections import dequePython's deque(maxlen=n) keeps only the last n lines, like tailHold the most recent n items of a stream without the list growing forever.30 Nov 2026 - Tip
import csvPython's csv.DictReader gives you each row as a dict keyed by the headerRead CSV files by column name instead of counting column positions.30 Nov 2026 - Tip
import json, os, tempfileOs.replace swaps in a new file in one step, on every platformWrite a file safely by writing a temp copy first and then replacing the original.30 Nov 2026 - Tip
python -X dev script.pypython -X dev turns on extra runtime checksEnables extra warnings and checks, such as unclosed files, while a script runs.28 Nov 2026 - Tip
python -P script.pypython -P stops the script directory from landing on sys.pathKeeps the script's own folder off the import path so local files cannot shadow modules.28 Nov 2026 - Tip
python -m compileall -q src/python -m compileall for a quick syntax check of a whole projectCompiles every Python file in a folder and reports files with syntax errors.28 Nov 2026 - Tip
from collections import CounterCollections.Counter.most_common for counting thingsCounts items in any list and returns the most frequent ones.28 Nov 2026 - Tip
import shutilShutil.which checks if a command exists before you call itReturns the full path of a command, or None when it is not installed.28 Nov 2026 - Tip
from contextlib import chdirContextlib.chdir changes directory and always changes backTemporarily changes the working directory for a block and restores it afterwards.28 Nov 2026 - Tip
from graphlib import TopologicalSorterGraphlib.TopologicalSorter orders tasks by their dependenciesSorts items so every one comes after the things it depends on.28 Nov 2026 - Tip
from textwrap import dedentTextwrap.dedent keeps indented multi-line strings tidyStrips shared indentation from a multi-line string so it can sit in indented code.28 Nov 2026 - Tip
>>> 'Arthur: three!'.lstrip('Arthur: ')Str.removeprefix instead of lstrip for a prefixRemoves an exact prefix from a string, unlike lstrip which strips a set of characters.28 Nov 2026 - Tip
from zoneinfo import ZoneInfoPython's zoneinfo gets Dutch summer and winter time right without pytzConverts times to Dutch local time with summer and winter time handled for you.27 Nov 2026 - Tip
from itertools import pairwisePython's itertools.pairwise walks a list in overlapping pairsGives each item of a list together with the next one, handy for differences and gaps.26 Nov 2026 - Tip
def to_gb(size_bytes):Python's doctest turns the examples in your docstrings into testsRuns the >>> examples in a module's docstrings and reports any whose output no longer matches.26 Nov 2026 - Tip
python3 -m zipapp myapp -o tool.pyz -m "cli:main" -p "/usr/bin/env python3"python -m zipapp packs a project into one runnable .pyz fileBundles code and dependencies into one executable file that needs only python installed.24 Nov 2026 - Tip
import logging, osPython logging.basicConfig can read the log level from an environment variableSwitches a script between quiet and verbose logging with an environment variable.24 Nov 2026 - Tip
from pathlib import PathPython pathlib with_suffix and with_name rename paths without string slicingBuilds a new path with another extension or filename without touching the disk.24 Nov 2026 - Tip
from pathlib import PathPython pathlib rglob finds files recursively without os.walkWalks a directory tree and yields matching files as Path objects, with sizes and text readers attached.24 Nov 2026 - Tip
uv add --script fetch.py requestsuv add --script writes python dependencies into the script itselfStores a script's dependencies in a comment block so one file runs anywhere with uv.24 Nov 2026
Other tips32
- Tip
f=$(mktemp --suffix=.json)Mktemp --suffix gives a temp file the extension a tool expectsCreate a unique temporary file that ends in a chosen extension3 Dec 2026 - Tip
dpkg --compare-versions 1.10 gt 1.9 && echo newerdpkg --compare-versions tells a script which version is newerCompares two Debian version strings and answers with the exit code.3 Dec 2026 - Tip
tmux wait-for build-donetmux wait-for blocks a script until another pane sends a signalPauses a command until something in another pane says it's done, without polling or sleep.2 Dec 2026 - Tip
awk '$1 >= "2026-11-30T02:00" && $1 < "2026-11-30T03:00"' app.logawk can cut a time window out of logs that use ISO timestampsExtract only the lines between two moments from a large file.1 Dec 2026 - Tip
tail -f --pid=1234 build.logtail can stop following a file once the writing process endsWatch a job's output and get your prompt back when the job finishes.1 Dec 2026 - Tip
jq empty config.jsonOne empty filter checks that a JSON file parsesCatch a broken config before the program that reads it does.1 Dec 2026 - Tip
jq -c --slurpfile u users.json 'Slurpfile joins two JSON files on a shared idAdd names from one export to records in another without writing a program.1 Dec 2026 - Tip
rclone lsf -R --files-only --format tsp remote:photosrclone lsf prints a plain file listing that scripts can readLists remote files with exactly the columns you ask for.1 Dec 2026 - Tip
echo 'aGVsbG8gd29ybGQ=' | openssl base64 -dOpenssl base64 -d decodes base64 on any system that has OpenSSLEncode and decode base64 with one command that works the same on Linux, macOS and BSD.30 Nov 2026 - Tip
. /etc/os-releaseSourcing /etc/os-release gives a Linux script the distro name and versionLet a script check which distribution and release it runs on, without parsing text.30 Nov 2026 - Tip
echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}'Awk int() cuts decimals off, and printf rounds half to evenShows how awk turns decimals into whole numbers, and why 2.5 can become 2.30 Nov 2026 - Tip
echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}'Awk -F '[:,]' splits a line on more than one separatorSplits fields on several different characters at once, using a regular expression as separator.30 Nov 2026 - Tip
tail -f access.log | cut -d' ' -f1 | uniqStdbuf -oL makes a command in the middle of a pipe print each line right awayStop a pipeline from holding back output until a buffer of several kilobytes is full.30 Nov 2026 - Tip
find . -name '*.txt' -exec sh -c 'for f; do cp -- "$f" "${f%.txt}.bak"; done' sh {} +find -exec sh -c lets each file go through a small scriptRuns a few commands per file from find, with the file name passed safely.30 Nov 2026 - Tip
if kill -0 "$pid" 2>/dev/null; thenKill -0 checks whether a Linux process is still alive without touching itTest from a script whether a PID still exists before you wait for it or start a new copy.30 Nov 2026 - Tip
awk 'BEGIN {RS=""} /[email protected]/' contacts.txtawk RS="" reads text in blocks separated by blank linesTreats each paragraph as one record, so you can filter whole blocks instead of single lines.30 Nov 2026 - Tip
awk -F, 'NR==FNR {name[$1]=$2; next} FNR>1 {print $1, ($2 in name ? name[$2] : "unknown"), $3}' names.csv orders.csvawk 'NR==FNR' looks up values from a second fileJoins two files on a shared column, like a small database lookup, in one awk command.30 Nov 2026 - Tip
awk NF file.txt > clean.txtawk NF removes empty lines, including the ones with only spacesDrops every line that has no visible content, also lines with just spaces or tabs.30 Nov 2026 - Tip
awk -F, 'NR>1 {s[$2]+=$3} END {for (k in s) print k, s[k]}' orders.csvawk 's[$1]+=$2' adds up a column per groupTotals a number column separately for each value in another column, like a GROUP BY.30 Nov 2026 - Tip
printf 'a b c\n' | awk -v OFS=, '{print}' # a b cAwk '$1=$1' with OFS turns spaces into commasRebuilds every line with a new field separator, for turning aligned output into CSV.30 Nov 2026 - Tip
awk -F, 'NR==1 {for (i=1; i<=NF; i++) col[$i]=i; next} {print $col["amount"]}' orders.csvawk can pick a CSV column by its header nameReads the header row once and then selects columns by name instead of by number.30 Nov 2026 - Tip
dpkg-query -W -f='${Package}\t${Version}\n' 'openssh-*'dpkg-query -W -f prints exactly the package fields you ask forPrints chosen fields of installed packages, such as name and version, in a format scripts can read.28 Nov 2026 - Tip
cp -r --update=none /mnt/user/photos/import/* /mnt/user/photos/library/Use cp --update=none instead of cp -n, which changed behaviour twiceCopies or moves files without overwriting existing ones, with an exit status you can predict.27 Nov 2026 - Tip
mv app.log "app-$(date -r app.log +%F).log"Date -r prints the modification time of a file in any format you likeShows when a file was last changed, formatted the way your script needs it.27 Nov 2026 - Tip
for i in $(seq -w 1 "$n"); doSeq -w counts with leading zeros, so file names sort the right wayPrints a number sequence with leading zeros, so numbered names line up and sort correctly.27 Nov 2026 - Tip
join <(sort hosts.txt) <(sort roles.txt)join matches two files on a shared column, like a tiny SQL joinCombines lines from two text files that share the same value in a key column.27 Nov 2026 - Tip
cat -E script.sh | headTr -d '\r' strips Windows line endings from a fileRemoves the hidden carriage returns that make Windows text files misbehave on Linux.27 Nov 2026 - Tip
wc -l < access.logwc -l < file gives you only the number, without the file namePrints just the line count of a file, so you can use it directly in a script.27 Nov 2026 - Tip
Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse }Measure-Command times any PowerShell commandRuns a PowerShell command and reports how long it took to finish.27 Nov 2026 - Tip
printf '%-20s %8s\n' NAME SIZEprintf '%-20s %8d' lines up shell output where echo cannotFormats text into fixed-width columns in a script.3 Jun 2026 - Tip
set -eset -e is switched off inside an if, so check shell exit codes yourselfExplains why set -e does not stop a function that runs as an if condition.14 Apr 2026 - Tip
ulimit -Snulimit -Sn only changes the open files limit of this linux shellRaises the open files limit for one shell session, up to the hard limit.9 Apr 2026
Network23
- Tip
curl -fsS --fail-early \curl fail-early stops at the first broken URL in a batchMake a multi URL curl command exit with an error as soon as one transfer fails.30 Nov 2026 - Tip
url = "https://example.com/data/latest.json"A curl config file can download a list of URLs, each under its own namePut url and output pairs in one file and fetch them all with one command.30 Nov 2026 - Tip
curl -q -fsS https://example.com/api/statuscurl -q as the first option ignores your .curlrcMake a script behave the same on every machine, whatever the local curl config says.30 Nov 2026 - Tip
echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}'Awk '{print $NF}' prints the last column, however many there areGrabs the last field of each line, even when lines have a different number of fields.30 Nov 2026 - Tip
dig +yaml example.com Adig +yaml prints the whole reply in a format scripts can parseGet dig's full answer as YAML, so a script can read fields instead of scraping text.30 Nov 2026 - Tip
curl --rate 2/s -O 'https://example.com/archive/page[1-20].html'curl rate limits how many requests it starts per secondSpace out a series of requests so an API or small server is not hit all at once.30 Nov 2026 - Tip
curl --no-clobber -O https://example.com/report.pdfcurl no-clobber keeps the old file and gives the new download a numberKeep the file you already have and let the new download land under a numbered name.30 Nov 2026 - Tip
prod_url=https://example.com${!name} reads a bash variable whose name is in another variablePick a setting like prod_url or test_url based on another variable.30 Nov 2026 - Tip
printf 'nginx 12.5\npostgres 300\n' | awk '{printf "%-10s %8.1f MB\n", $1, $2}'Awk printf lines up columns into a neat tableFormats output into aligned columns with fixed widths and decimals.30 Nov 2026 - Tip
resolvectl query -4 --legend=no example.comresolvectl query --legend=no prints only the answerPrints resolvectl lookup results without headers, so scripts get only the answers.28 Nov 2026 - Tip
curl --parallel --remote-name-all \curl -Z runs several downloads in parallelStarts every download on the command line at once instead of waiting for each one to finish.28 Nov 2026 - Tip
|| { echo "request failed: $resp" >&2; exit 1; }Curl --fail-with-body keeps the error page and still returns exit code 22Makes curl exit with code 22 on an HTTP error but still prints the server's error message.28 Nov 2026 - Tip
curl --create-dirs -o /mnt/user/appdata/<app>/downloads/2026/data.zip \curl --create-dirs makes the folder for your -o pathCreates the missing folders of a download path so you do not need a separate mkdir.28 Nov 2026 - Tip
curl --variable [email protected] \curl --variable and --expand-data fill a request from variablesLets curl hold variables and insert them, correctly escaped, into the URL or request body.28 Nov 2026 - Tip
curl https://example.com/ --next -d 'name=test' https://example.com/api/itemscurl --next sends two different requests in one commandSplits one curl command into separate requests that each keep their own options.28 Nov 2026 - Tip
curl --max-filesize 50M -O https://example.com/blocklist.txtcurl --max-filesize refuses a download that is bigger than you expectStops curl from downloading a file that is larger than the size limit you set.28 Nov 2026 - Tip
https://example.com/file[1-100].txtCurl URL ranges like [01-05] with -o #1 fetch a numbered seriesExpands ranges and lists inside a URL so curl downloads a whole numbered series in one command.28 Nov 2026 - Tip
curl --fail --remove-on-error -o /mnt/user/appdata/<app>/list.txt https://example.com/list.txtcurl --remove-on-error deletes the half-written file after a failureRemoves the output file when a curl transfer fails, so no half-downloaded file is left to use.28 Nov 2026 - Tip
curl --skip-existing --create-dirs --parallel --remote-name-all \curl --skip-existing leaves a file alone when it is already thereMakes curl skip a download when a file with that name already exists locally.28 Nov 2026 - Tip
declare -A port=(declare -A gives bash a lookup table with names as keysStores values under names in a bash script, so you can look them up by key.27 Nov 2026 - Tip
curl --connect-timeout 5 --max-time 30 -fsS https://example.com/apicurl --max-time keeps a hung request from blocking your scriptAborts a request that takes too long to connect or to finish.24 Nov 2026 - Tip
curl --retry 5 --retry-delay 2 --retry-all-errors -fsS -O https://example.com/file.tgzcurl --retry-all-errors waits out a service that is still startingRepeats a failed request several times, even on errors curl normally treats as final.24 Nov 2026 - Tip
curl -fsS https://example.com/health || echo "check failed"curl -fsS gives scripts a real exit code and keeps error messagesMakes curl fail on HTTP errors with an exit code while still printing error messages.6 May 2026
Storage12
- Tip
readonly BACKUP_DIR=/srv/backupreadonly keeps a shell script from changing an important path by accidentLock a variable after you set it, so later code cannot overwrite it.30 Nov 2026 - Tip
env -i ./backup.shenv -i runs a command with an empty environment, like cron and systemd doReproduce the 'works in my shell, fails in cron' problem on purpose.30 Nov 2026 - Tip
time rsync -a /srv/data/ /mnt/backup/data/TIMEFORMAT makes the bash time keyword print one tidy lineGet a short, readable timing for any command or block in a script.30 Nov 2026 - Tip
if ! mountpoint -q /mnt/backup; thenMountpoint -q tells a script whether a folder is really mountedReturns success only when a folder is a mount point, so scripts can check first.28 Nov 2026 - Tip
printf '0 3 * * * /usr/local/bin/backup.sh' | crontab -The last line of a crontab needs a newline, or cron may ignore itWarns that cron may treat a crontab as broken when its last line has no newline at the end.28 Nov 2026 - Tip
logger -t backup "nightly sync finished"logger -t lets a script write its own lines to the system logWrites a tagged message from a script to the system log so you can find it later.28 Nov 2026 - Tip
df -P | awk -v max="$limit" 'NR > 1 && $5+0 > max {print $6, $5}'Awk -v passes a shell variable into an awk programHands a value from your shell script to awk without breaking the quoting.27 Nov 2026 - Tip
f="backup-2026-11-27.tar.gz"${var:offset:length} cuts a piece out of a bash stringTakes a fixed part of a string in bash, counting from the start or the end.27 Nov 2026 - Tip
timeout -k 5 30 ./backup.shtimeout stops a command that hangsStops a command after a set time, and force-kills it if it will not quit.23 Oct 2026 - Tip
df -h | tr -s ' ' | cut -d' ' -f1,5Tr -s ' ' makes cut work on aligned terminal columnsSqueezes repeated spaces so cut can pick columns from padded output.22 Apr 2026 - Tip
./backup.sh 2>&1 | tee -a backup.logTee -a writes terminal output to a log and still shows itShows output on screen and appends the same output to a log file.18 Apr 2026 - Tip
shellcheck backup.shshellcheck finds quoting mistakes in a shell script before they runScans a shell script for common mistakes such as unquoted variables.15 Apr 2026
Git9
- Tip
git rev-parse --show-toplevelgit rev-parse --show-toplevel prints the root folder of your repositoryPrints the absolute path of the top folder of the current Git repository, from any subfolder.2 Dec 2026 - Tip
git ls-files --others --exclude-standardgit ls-files --others --exclude-standard lists untracked files, one per linePrints only the new files Git doesn't track yet, skipping everything in .gitignore, as plain paths.2 Dec 2026 - Tip
git merge-base --is-ancestor main featgit merge-base --is-ancestor tells a script if one commit is already in anotherAnswers yes or no through the exit code whether a commit is part of another commit's history.2 Dec 2026 - Tip
git ls-tree -r --name-only maingit ls-tree -r --name-only lists the files in any commit without checking it outLists every file in a commit or branch as plain paths, without touching your working folder.2 Dec 2026 - Tip
git show-ref --verify --quiet refs/heads/featuregit show-ref --verify --quiet checks if a branch or tag existsTells a script by exit code whether a branch or tag with an exact name exists.2 Dec 2026 - Tip
gh pr checks --watch --fail-fastgh pr checks can watch a pull request and stop at the first failing checkWatches the checks of a pull request and quits as soon as one fails.30 Nov 2026 - Tip
gh run watch --exit-statusgh run watch with an exit status waits for a workflow and fails when it failsFollows a running Actions workflow in the terminal and returns its result.30 Nov 2026 - Tip
gh release download -R cli/cli --pattern '*linux_amd64.tar.gz' -D /tmp/ghgh release download with a pattern grabs only the release file you needDownloads only the matching assets of a release, without the browser.30 Nov 2026 - Tip
$r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latestInvoke-RestMethod turns a JSON API answer into PowerShell objectsCall a REST API and work with the fields directly, without parsing JSON yourself.30 Nov 2026
Docker7
- Tip
docker run -d --cidfile /tmp/app.cid nginxdocker run --cidfile saves the new container's ID to a fileWrites the ID of the container you start into a file, so a script can find it later.2 Dec 2026 - Tip
docker compose wait migratedocker compose wait blocks until a Compose service has stoppedMake a script wait for a one-shot service to finish before it continues.30 Nov 2026 - Tip
exec "$@"exec "$@" at the end of an entrypoint shell script passes signals onLet the real program replace your wrapper script so stop signals reach it.30 Nov 2026 - Tip
docker wait nightly-jobdocker wait blocks until a container stops and prints its exit codeWaits for a container to stop, then prints its exit code, which is handy in scripts.28 Nov 2026 - Tip
docker compose up --exit-code-from tests --builddocker compose up --exit-code-from passes a service's exit code onRuns a stack in the foreground and exits with the exit code of the service you name.28 Nov 2026 - Tip
if systemctl is-active --quiet docker.service; thenSystemctl is-active --quiet gives a script a plain yes or noReturns exit code 0 when a unit is active, so shell scripts can test a service without parsing text.28 Nov 2026 - Tip
docker compose exec -T db pg_dump -U postgres mydb > backup.sqlUse docker compose exec -T when a script runs itRuns a command in a service without a terminal, so output can be piped or redirected cleanly.17 Jul 2026
Web4
- Tip
wp post create ./draft.html --post_title='Release notes' --post_status=draft --porcelainwp post create reads the WordPress post body from a filePublishes or drafts a post whose content comes from an HTML file on disk.30 Nov 2026 - Tip
if wp plugin is-active woocommerce; thenWp plugin is-active gives a WordPress script a yes or noChecks whether one plugin is active and answers with exit code 0 or 1.30 Nov 2026 - Tip
if ! wp core is-installed 2>/dev/null; thenWp core is-installed lets a script check for WordPress by exit codeReturns success when WordPress is installed, so a deploy script can branch on it.30 Nov 2026 - Tip
wp eval 'echo get_option( "blogname" ), PHP_EOL;'wp eval runs a line of PHP inside a fully loaded wordpressExecutes a snippet of PHP with WordPress loaded, without writing a plugin or a template.1 Apr 2026
AI2
- Tip
claude auth status --textclaude auth status --text tells you when your Claude Code login endsShows which login Claude Code uses and, on recent versions, when a claude.ai sign-in expires.3 Dec 2026 - Tip
claude agents --jsonclaude agents --json lists background sessions for your scriptsPrints your active Claude Code background sessions as a JSON array for scripts.28 Nov 2026
Mac2
- Tip
/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" /Applications/Safari.app/Contents/Info.plistPlistBuddy reads one value from a macOS plist, like an app's versionRead a single key such as an app's version from a property list file.30 Nov 2026 - Tip
osascript -e 'id of app "Safari"'osascript -e 'id of app' prints the bundle ID of any Mac appGet an app's bundle identifier for defaults, profiles or scripts in one line.30 Nov 2026
Media2
- Tip
name=jellyfin${var^^} and ${var,,} change the case of a bash variableTurns a bash variable into upper or lower case without tr or awk.27 Nov 2026 - Tip
v="sonarr-4.0.10"[[ $s =~ regex ]] fills BASH_REMATCH with the parts that matchedMatches a regular expression in bash and gives you the captured parts without sed.27 Nov 2026
Security1
Nothing matches.