tips
78 tips Shell
One command, setting or habit at a time about Shell: what it does, the line to copy and a caveat or two.
Linux and shell 29
-
List the folders zoxide remembers, with scores, to understand its jumps.
zoxide query -ls project -
Two bash variables hold the current Unix time in seconds, or with microseconds.
echo $EPOCHSECONDS -
Send all output of a script to a log file while you still see it on screen.
exec > >(tee -a /var/log/nightly.log) 2>&1 -
Add a random delay so many machines do not hit the same server at once.
sleep $((RANDOM % 300)) -
Write a script or config with dollar signs from a here-document, untouched.
EOF -
Append a line to a file owned by root, because sudo echo > file fails.
echo '203.0.113.10 nas.example.com' | sudo tee -a /etc/hosts >/dev/null -
Turn a config template with $VARIABLES into a real file without sed.
envsubst < site.conf.tpl > site.conf -
Let the real program replace your wrapper script so stop signals reach it.
exec "$@" -
Open a log file once and write to it many times through a number.
exec 3>>report.log -
Break a comma separated line into array elements without cut or awk.
IFS=, read -ra hosts <<< "$line" -
Load a small file into a variable without starting an extra cat process.
version=$(< VERSION) -
Use colours and progress output only when output goes to a terminal.
if [ -t 1 ]; then -
Fix 'No such file or directory' after moving or reinstalling a program.
hash -r # forget everything -
Runs the last command of a pipeline in the current shell so its variables survive.
shopt -s lastpipe -
Writes the current date into a shell variable using only the printf builtin.
printf -v stamp '%(%Y-%m-%d_%H%M)T' -1 -
Prompts for input without echoing it and gives up after a set number of seconds.
read -r -s -p "Token: " token; echo -
Replaces Ctrl-R with a fuzzy, live-filtered search of your shell history.
eval "$(fzf --bash)" -
Writes tab and newline characters in a shell string with ANSI-C quoting.
IFS=$'\t' read -r name size <<< $'backup.tar\t1048576' -
Sends the output of several commands to one file with a single redirect.
-
Formats text into fixed-width columns in a script.
printf '%-20s %8s\n' NAME SIZE -
Resumes the script as soon as any one background job has finished.
wait -n -
Creates many folders at once by letting the shell expand braces.
mkdir -p backup/{2025,2026}/{01..12} -
Lets cd find folders by name in a list of parent directories.
export CDPATH=.:~/dev:~/dev/work -
Reads short command line flags in a script with a built-in parser.
while getopts 'f:v' opt; do -
Reads the lines of a command into a bash array without word splitting problems.
mapfile -t logs < <(find /var/log -name '*.log') -
Gives a command a string as input without a pipe or a temporary file.
IFS=@ read -r user host <<< "jordi@nas" -
Strips an extension or a directory from a variable with built-in pattern removal.
f=/srv/media/holiday.final.mp4 -
Uses a default value when a variable is unset or empty.
backup_dir=${BACKUP_DIR:-/var/backups} -
Keeps variables set in a read loop by feeding it with process substitution.
while read -r line; do count=$((count+1)); done < <(ls /etc)
Safe scripts 16
-
Create a unique temporary file that ends in a chosen extension
f=$(mktemp --suffix=.json) -
Make a script quit when cd fails, before it runs commands in the wrong folder.
cd /srv/app/releases || exit 1 -
Lock a variable after you set it, so later code cannot overwrite it.
readonly BACKUP_DIR=/srv/backup -
Stop a file called -rf from being read as an option by rm or mv.
echo ./* -
Keep exit codes between 0 and 255, because larger numbers wrap around.
bash -c 'exit -1'; echo $? # 255 -
Replace a config or data file in one step, so readers never see it half written.
tmp=$(mktemp ./hosts.json.XXXXXX) -
Declare and assign on separate lines so a failure inside $( ) is not lost.
local out=$(false) -
Blocks the > operator from overwriting existing files unless you use >|.
set -o noclobber -
Makes bash exit with an error instead of treating an unset variable as empty.
set -u -
Prints a value with escaping, so spaces and special characters survive when it is pasted back into a shell command.
printf '%q\n' "$name" -
Runs a cleanup command whenever the script exits, including after an error.
trap 'rm -rf "$tmp"' EXIT -
Stops the script with an error when a variable is empty, before a delete can hit the wrong path.
rm -rf "${BUILD_DIR:?BUILD_DIR is not set}"/* -
Makes a pipeline report failure when any command in it fails, not only the last one.
set -o pipefail -
Scans a shell script for common mistakes such as unquoted variables.
shellcheck backup.sh -
Prints the line number and command when a bash script hits an error.
trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR -
Explains why set -e does not stop a function that runs as an if condition.
set -e
Globbing 10
-
Preview a pattern-based bulk rename in zsh before running it.
zmv -n '(*).log' '$1.txt' -
Controls whether a pattern like .* also matches the current and parent folder entries.
shopt globskipdots -
Keep *.bak or *~ files out of every * you type in that session.
GLOBIGNORE='*.bak:*~' -
Pick files by a digit or letter in a fixed spot, without regex.
ls -
Match photo.JPG and photo.jpg with one pattern.
shopt -s nocaseglob -
Match a list of extensions without the empty results that braces leave.
shopt -s extglob -
Lets the * wildcard include files whose names start with a dot.
shopt -s dotglob -
Makes a bash glob that matches no files disappear, so loops skip instead of failing.
for f in *.log; do -
Lists or selects every file except the ones matching a pattern, using Bash extended globs.
shopt -s extglob -
Turns on ** in Bash so one pattern matches files in every subfolder.
shopt -s globstar
Shortcuts 10
-
Clear the terminal without losing the half-typed command.
docker compose logs --tail 50 web # now at the top of a clean screen -
Fix a typo like sl or sytemctl with one key instead of retyping.
^ cursor on the i, press Ctrl-t -
Jump over words on the command line instead of holding the arrow keys.
Alt-b back one word -
Change a word to upper, lower or title case while you type a command.
Alt-u UPPERCASE the rest of the word -
Parks a half-typed command so you can run another one first and paste it back.
Ctrl-U # cut from the cursor to the start of the line -
Inserts the last argument of the previous command at the cursor, and cycles back through older ones.
mkdir ~/projects/new-site -
Expands to a command with the file name and a .bak copy, saving you from typing the path twice.
cp /etc/ssh/sshd_config{,.bak} -
Runs a shell command from the Claude Code prompt and puts the output in the conversation.
! npm test -
Pastes the last word of your previous command at the cursor, so you do not retype paths.
cd Alt+. -
Reruns the previous command with sudo in front of it, so you do not retype it.
sudo !!
Config and keys 3
-
Lets Tab complete Documents when you type doc, and lists every match at once.
set completion-ignore-case on -
Moves into a folder when you type its name, without typing cd.
shopt -s autocd -
Repeats the previous command after fixing one word with a quick substitution.
systemctl status ngnix
Shell basics 3
-
Know why cd and variables from a script vanish, and when source keeps them.
source s.sh; echo "$PWD $X" # /tmp 1 -
Forward the arguments of a script or function without breaking names with spaces.
f() { -
Keeps a numbered stack of folders so you can hop back and forth between them.
pushd /var/log
Text processing 3
-
Makes xargs split its input only at newlines, so names with spaces stay whole.
printf '%s\n' "holiday photo.jpg" "notes 2026.txt" | xargs -d '\n' -n1 echo -
Prints a file with tabs, line ends and control characters made visible.
cat -A docker-compose.yml -
Hands a value from your shell script to awk without breaking the quoting.
df -P | awk -v max="$limit" 'NR > 1 && $5+0 > max {print $6, $5}'
History and debugging 2
-
See what a function in your shell really does, and where it came from.
declare -f mkcd -
Shows the file and line number in front of every command bash traces with set -x.
set -x
Files and media 1
-
Leaves Mac and git clutter out of a zip archive you make in the terminal.
zip -r site.zip site -x '*.DS_Store' '*/.git/*'
systemd 1
-
Returns exit code 0 when a unit is active, so shell scripts can test a service without parsing text.
if systemctl is-active --quiet docker.service; then
Nothing in this filter yet.