tips
178 tips Linux and shell
One command, setting or habit at a time about Linux and shell: what it does, the line to copy and a caveat or two.
Linux and shell 178
-
List the folders zoxide remembers, with scores, to understand its jumps.
zoxide query -ls project -
Use fzf's Alt-C binding to change directory with fuzzy search.
eval "$(fzf --bash)" -
Adds a last line with how many lines are only in file one, only in file two, and in both.
comm --total a.txt b.txt -
Leaves out files and folders matching a pattern when comparing two directories recursively.
diff -r -x .git -x '*.log' one two -
Sets an environment variable in each parallel xargs job, holding the slot number it runs in.
printf '%s\n' a b c d e f | xargs -n1 -P3 --process-slot-var=SLOT sh -c 'echo "slot $SLOT got $0"; sleep 0.2' -
Reverses a patch, so the files go back to how they were before it was applied.
patch -R g.txt < f.patch -
Two bash variables hold the current Unix time in seconds, or with microseconds.
echo $EPOCHSECONDS -
Explains why `cmd > file 2>&1` and `cmd 2>&1 > file` send errors to different places.
cmd > file 2>&1 -
Pastes the word under the cursor into a command or search you are typing in Vim.
:%s/<Ctrl-r><Ctrl-w>/newname/g -
An empty pattern in a substitute command reuses your last search, so you can look first and replace after.
/oldname -
Reads text from a pipe into a new Vim buffer so you can search and edit it.
find . -name "*.conf" | vim - -
Starts Vim with default settings and no personal config, to find out whether your setup causes a problem.
vim --clean file.txt -
Rewraps a paragraph or a selection to a fixed line width, such as 72 characters.
:set textwidth=72 -
Opens a file with Vim's navigation and search, but blocks accidental saves.
view /etc/fstab -
Turns on line numbers permanently in nano, so you don't need the -l flag each time.
nano -l file.txt -
Runs Neovim's self-checks and reports missing tools, broken plugins and provider problems.
:checkhealth -
Look at the end of a file that has very long lines or none.
tail -c 2000 export.json -
Watch a job's output and get your prompt back when the job finishes.
tail -f --pid=1234 build.log -
Watch more than one log in a single terminal window.
tail -f /var/log/nginx/access.log /var/log/nginx/error.log -
Count the pieces a large file is split into on disk.
filefrag /var/lib/libvirt/images/vm1.qcow2 -
See allocated and unallocated space when df gives a misleading answer.
sudo btrfs filesystem usage /mnt/pool -
Sort a directory listing by size, with readable units.
ls -lhS /var/log -
Identify a file by its contents, whatever its extension claims.
file photo.jpg data.bin -
Sort names with numbers in them the way a person would count.
ls -v -
Read or pipe a single file from a zip archive without extracting everything.
unzip -l site.zip -
Merge files into a folder while keeping whatever is already there.
mv -n card2/*.jpg ~/Pictures/all/ -
Opens a file browser inside Vim to pick another file.
:Ex -
Connects the command xargs starts to your terminal, so editors and prompts work normally.
grep -l 'TODO' *.py | xargs -o vim -
Picks a recently edited file from a numbered list.
:browse oldfiles -
Loop over all settings like APP_PORT and APP_HOST without naming each one.
APP_HOST=example.com -
Saves your favourite gh commands as short aliases, with arguments.
gh alias set mine 'pr list --author @me' -
Returns to previous cursor spots after a search or a jump.
Ctrl-o -
Starts Vim with the cursor on a line or search match.
vim +/listen /etc/nginx/nginx.conf -
Puts two versions next to each other in columns, which is easier to read for short config files.
diff -y -W 100 old.conf new.conf -
Get some elements of an array, like all but the first, without a loop.
a=(a b c d e) -
Creates a patch of a whole folder that includes new and deleted files, not only changed ones.
diff -Naur original/ changed/ > fix.patch -
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 -
Shows every command xargs is about to run and waits for you to confirm it.
find . -name '*.orig' -print0 | xargs -0 -p rm -
Pastes your last copy even after a delete replaced it.
"0p -
Add a random delay so many machines do not hit the same server at once.
sleep $((RANDOM % 300)) -
Brings back your previous selection to work on it again.
gv -
Explains xargs exit codes, so a script can tell whether every command it ran succeeded.
find . -name '*.gz' -print0 | xargs -0 -n 1 gzip -t -
Replaces lines in the buffer with the output of a command.
:%!sort -u -
Reproduce the 'works in my shell, fails in cron' problem on purpose.
env -i ./backup.sh -
Stop a pipeline from holding back output until a buffer of several kilobytes is full.
tail -f access.log | cut -d' ' -f1 | uniq -
Re-indents a file using Vim's indent rules for the language.
gg=G -
Tests a patch file against your folder first, so a failed patch doesn't leave half-changed files.
patch -p1 --dry-run < ../fix.patch -
Jumps to the next place a word appears without typing it.
* -
Tell an unset variable apart from one that is set to an empty string.
[[ -v b ]] && echo set || echo unset # set -
Loop over positions or keys of an array, also after removing elements.
hosts=(web db cache) -
Opens a path from your text without typing it.
gf -
Applies the same change to all buffers in one go.
:bufdo %s/oldhost/newhost/ge | update -
Compares a Windows file with a Unix file without every line showing up as changed.
diff --strip-trailing-cr windows.txt unix.txt -
Run jobs in parallel and still check which of them failed.
wait "$db_pid"; db_status=$? -
Write a script or config with dollar signs from a here-document, untouched.
EOF -
Compares two files and moves differences between them.
vimdiff nginx.conf nginx.conf.new -
Converts a file with Windows line endings back to Unix ones.
:set ff=unix -
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 "$@" -
Count characters or array items without wc or a loop.
key='abc123xyz' -
Pick a setting like prod_url or test_url based on another variable.
prod_url=https://example.com -
Uses diff's exit code to act only when a file really changed.
if ! diff -q /etc/nginx/nginx.conf /srv/backup/nginx.conf > /dev/null; then -
Let a user pick an option by number without writing your own menu loop.
select action in start stop status quit; do -
Creates a pull request from the terminal, taking title and body from your commits.
gh pr create --fill -
Identifies odd characters by their decimal, hex and octal code.
ga -
Leaves out changes in lines such as generated dates, so two exports can be compared.
diff -I '^# generated' old/app.conf new/app.conf -
Open a log file once and write to it many times through a number.
exec 3>>report.log -
Jumps from the terminal to a file, line, issue or settings page of the repository.
gh browse src/app.py:42 -
Puts files next to each other in one Vim screen.
:vsplit config.example.yml -
Read only the log lines since a service last started, without looking up the time.
journalctl -u nginx --since "$(systemctl show -p ActiveEnterTimestamp --value nginx)" -
Break a comma separated line into array elements without cut or awk.
IFS=, read -ra hosts <<< "$line" -
Keeps each input line together as the arguments of one command run.
printf 'a b\nc d\n' | xargs -L 1 echo line: -
Add to a string or array without repeating the variable name on the right.
s=foo; s+=bar; echo "$s" # foobar -
Hides differences that are only extra or fewer spaces, so the real changes stand out.
diff -b old.conf new.conf -
Create a symlink with a relative path without counting the dots yourself.
ln -sr /srv/site/shared/uploads /srv/site/current/uploads -
Wait for a file, a service or a disk to change without writing a loop.
watch -g -n 5 ls /srv/inbox && echo 'new file in the inbox' -
Shows the exact commands xargs builds, which makes a pipeline easy to check and debug.
printf 'x\ny\n' | xargs -t touch -
Free the space of a runaway log without deleting the file or restarting the program.
truncate -s 0 /var/log/app/debug.log -
Searches a whole project from inside Vim and jumps through results.
:vimgrep /TODO/ **/*.py -
Calculates something and inserts the answer while you type.
Ctrl-r =19*23<Enter> -
Changes the case of a word, a line or a selection.
gUiw -
Load a small file into a variable without starting an extra cat process.
version=$(< VERSION) -
Runs a shell or a command inside Vim, next to your file.
:terminal -
Prints the system's limit on command length and the buffer size xargs really uses.
xargs --show-limits < /dev/null -
Get a short, readable timing for any command or block in a script.
time rsync -a /srv/data/ /mnt/backup/data/ -
Copy a big folder in seconds as hard links, as a quick snapshot before you change things.
cp -al photos photos-before-cleanup -
Search all commands, aliases and functions your bash knows about.
compgen -c | sort -u | grep '^systemd-' -
Bookmarks a spot in a file so you can return to it.
ma -
Adds a prefix to a column of lines in one edit.
Ctrl-v -
Use colours and progress output only when output goes to a terminal.
if [ -t 1 ]; then -
Changes the next search match, then repeats it where you choose.
/oldName -
Splits a list into fixed-size groups, so each command run gets exactly the number of arguments it needs.
printf 'old1.txt new1.txt\nold2.txt new2.txt\n' | xargs -n 2 mv -
Get the PID of the current subshell, where $$ still shows the parent.
echo "main: $$ $BASHPID" -
Fix 'No such file or directory' after moving or reinstalling a program.
hash -r # forget everything -
Makes invisible whitespace visible while you edit.
:set list listchars=tab:>-,trail:~,eol:$ -
Compares two folder trees and lists only the files that are missing or changed.
diff -qr /srv/site /mnt/backup/site -
Takes the items from a file so the command that xargs runs can still use the keyboard.
xargs -a hosts.txt -n 1 ssh-keygen -R -
Records a series of keystrokes once and repeats it on other lines.
qa -
Collapses indented blocks so you can see a file's outline.
:set foldmethod=indent -
Runs the last command of a pipeline in the current shell so its variables survive.
shopt -s lastpipe -
Finds the directory of the running script so it can load files next to it.
source "$script_dir/config.env" -
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 -
Checks whether a TCP port accepts connections using only bash, no nc needed.
timeout 3 bash -c '</dev/tcp/192.168.1.x/443' && echo open || echo closed -
Resolves a chain of symlinks and prints the real absolute path of the target.
readlink -f /usr/bin/python3 -
Opens your Vim command history as a buffer, so you can edit an old command and rerun it.
(move to the line with k, edit it) -
Saves Vim undo history in a file so you can still undo after reopening the document.
set undofile -
Jumps back to the place where you last left Insert mode and starts typing again there.
gi back to where you stopped typing, in Insert mode -
Counts how many times a pattern appears in the file, using the substitute command's n flag.
:%s/error//gn -
Turns a bash variable into upper or lower case without tr or awk.
name=jellyfin -
Stores values under names in a bash script, so you can look them up by key.
declare -A port=( -
Passes an array to a bash function by name, so the function can change the original.
local -n _list=$1 -
Swaps text inside a bash variable, once or everywhere, without calling sed.
f="my holiday photo.jpg" -
Matches a regular expression in bash and gives you the captured parts without sed.
v="sonarr-4.0.10" -
Times a script or one step of it in bash without calling date.
SECONDS=0 -
Takes a fixed part of a string in bash, counting from the start or the end.
f="backup-2026-11-27.tar.gz" -
Saves every overwritten file as a numbered copy, so you can always go back.
cp --backup=numbered nginx.conf /etc/nginx/nginx.conf -
Copies files into a target folder while keeping the directory path they came from.
mkdir -p ~/config-export -
Clones a big file in an instant on filesystems that support copy on write.
cp --reflink=always vdisk1.img vdisk1-before-update.img -
Copies or moves files without overwriting existing ones, with an exit status you can predict.
cp -r --update=none /mnt/user/photos/import/* /mnt/user/photos/library/ -
Shows when a file was last changed, formatted the way your script needs it.
mv app.log "app-$(date -r app.log +%F).log" -
Replaces a symlink that points to a directory, rather than adding a link inside that directory.
ln -sf /srv/app/releases/v2 /srv/app/current -
Swaps the names of two files or directories at once, with nothing in between.
mv -T --exchange /srv/site/html /srv/site/html-new -
Prints a number sequence with leading zeros, so numbered names line up and sort correctly.
for i in $(seq -w 1 "$n"); do -
Gives a file the same modification time as another file, or any date you choose.
touch -r notes.orig.md notes.md -
Places each input line at a chosen spot in the command, not just at the end.
find . -maxdepth 1 -name '*.conf' | xargs -I {} cp {} {}.bak -
Stops xargs from running the command when the pipeline before it produced no input.
docker ps -aq --filter status=exited | xargs -r docker rm -
Adds to or subtracts from numbers in Vim, or numbers a list in one go.
Ctrl-A add 1 to the number at or after the cursor -
Jumps back to the places you edited in Vim, newest first.
`. go to the last change -
Repeats a set of normal-mode keystrokes on every line in a range.
:%norm A; -
Highlights misspelled words in Vim and lets you pick a correction from a list.
:setlocal spell spelllang=en_us -
Shows progress, speed and time left for data going through a pipe.
pv backup.tar.gz | tar xz -
Turns a messy path with dots and symlinks into a clean absolute path, or one relative to a folder.
realpath ../../data/./file.txt -
Compares two files byte by byte and reports where they first differ, or all differing bytes with -l.
cmp -l file1.bin file2.bin | head -
Converts plain numbers into human-readable sizes, and works on any number that you pipe into it.
echo 1610612736 | numfmt --to=iec -
Deletes all lines containing a pattern, or all lines not containing it, in one command.
:g/^#/d -
Runs a shell command and inserts what it prints below the current line.
:r !date -
Sorts the lines of a file or a selection, with options for numbers, case and duplicates.
:sort -
Writes all modified buffers to disk in one command, and optionally exits Vim.
:wa -
Compares two files and prints only the changes, with a few lines of context, in the format patch tools expect.
diff -u nginx.conf.bak nginx.conf -
Blocks until something happens to a file or folder, so a script can react without polling.
inotifywait -m -e close_write /srv/inbox -
Splits a large file into fixed-size parts with numbered names, which cat can join back together.
split -b 1G -d --additional-suffix=.part big.iso big.iso. -
Turns plain-English dates such as yesterday or next friday into a real date on the command line.
date -d '2 days ago' +%F -
Stops processes by exact name, so killing 'vim' does not also take down 'gvim' or 'vimdiff'.
pkill -x node -
Prints the lines of a file in reverse order, which puts the newest log entry on top.
tac /var/log/app.log | head -n 20 -
Jumps the text back or forward in time instead of stepping through undo one change at a time.
:earlier 10m -
Draws the files and folders of a directory as a tree, cut off at the depth you choose.
tree -L 2 -
Adds a column with the filesystem type, so you see what is on each mounted disk.
df -hT -
Replaces Ctrl-R with a fuzzy, live-filtered search of your shell history.
eval "$(fzf --bash)" -
Switches to the branch of a GitHub pull request using only its number.
gh pr checkout 123 -
Saves a file that vim opened without permission, using sudo from inside the editor.
:w !sudo tee % > /dev/null -
Sends both normal output and error messages through the pipe, shorter than 2>&1.
make 2>&1 | less -
Stops a command after a set time, and force-kills it if it will not quit.
timeout -k 5 30 ./backup.sh -
Compares the output of two commands directly, without saving them to temporary files.
diff -
Follows a log file by name so it keeps working after the file is rotated.
tail -F /var/log/nginx/access.log -
Shows each network interface with its state and addresses on a single line.
ip -br a -
Gives one extra named user access to a folder without touching owner or group.
sudo setfacl -m u:alice:rX /srv/data -
Runs a command on several inputs at the same time instead of one after another.
find . -name '*.png' -print0 | xargs -0 -n 1 -P 4 optipng -
Sets sensible permissions in one pass: execute only on directories and already-executable files.
chmod -R u=rwX,go=rX /srv/site -
Prints which mounted filesystem a given path lives on.
findmnt -T /var/lib/docker -
Shows every disk and partition with its filesystem type, label, UUID and mount point.
lsblk -f -
Lets you change a systemd service in a separate file that updates will not overwrite.
sudo systemctl edit nginx -
Shrinks the systemd journal to a size you pick by deleting the oldest logs.
journalctl --disk-usage -
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) -
Prints CPU, memory, swap and I/O wait figures once per second.
vmstat 1 5 -
Runs a heavy command with the lowest CPU and disk priority.
nice -n 19 ionice -c3 tar -czf /backup/www.tar.gz /var/www
Nothing in this filter yet.