# lore

> lore is a free terminal app for Linux and macOS (and Windows through WSL) that lists every command you can type (programs on your PATH, your shell's builtins and your aliases) in one A to Z list, with an offline page for each: what it does, the examples you need, which package it came from, and its manual.

- Latest version: 0.4.9 (2026-11-25)
- Platforms: Linux and macOS, and Windows inside WSL; shells: bash, zsh and fish
- License: the lore licence (https://github.com/guhhammer/lore/blob/main/LICENSE): free to use at home or at work and to share unchanged; changes only as contributions; versions up to 0.4.6 are MIT
- Written in Rust, one binary, built on ratatui
- About 9,100 command pages built into the binary; pages in 41 languages when a translation exists; the interface in 12
- 100 recipes: short task pages that chain commands
- 33 colour palettes, the terminal's own colours by default
- Also: 46 tool cheat sheets, Learn X in Y minutes pages for 201 languages, the 850 DevDocs sets to download, and the beacon (what people use most, from Debian's and Homebrew's public numbers)
- A Claude Code plugin whose skill answers command-line questions from lore, offline
- Works offline. With Internet on, each page can add a cht.sh cheat sheet and the beacon refreshes weekly; Internet off stops every request lore makes on its own
- Shell history is only read, on the user's machine, to rank the commands they run most; it can be turned off
- Source and downloads: https://github.com/guhhammer/lore (https://github.com/guhhammer/lore/releases)
- Author: Gustavo Hammerschmidt (https://guhhammer.dev)

## What lore lists

- Programs: the executables on your $PATH, plus the places a $PATH often leaves out (/usr/sbin, Homebrew, MacPorts, Nix, Snap, Flatpak, ~/bin, ~/.cargo/bin, ~/go/bin, /opt/*/bin).
- Your shell's own commands: the builtins and keywords of bash, zsh or fish.
- Your aliases, read from your shell's startup files, each with what it runs; fish functions too.
- Subcommands with a page, such as git commit or docker run, under their program.
- Categories after each name, with `danger` in red for commands that can destroy data.
- Recipes: short task pages that chain commands.
- Topics beside the commands: recipes, languages, docs, tools and the beacon, plus your own most used, recent and bookmarks.

## Usage

- `lore` opens the list; `lore tar` opens tar's page straight away, like `man tar`; `lore git commit` opens a subcommand's page.
- `lore --print tar` writes the page as plain text, for pipes and scripts.
- `lore explain "tar -xzvf a.tgz"` says what each word of a command line does, from the man pages, offline.
- `lore search compress folder` prints the search's results as plain text, best first, for scripts and agents.
- Keys: ↑ ↓ move, Enter opens a page, ← → switch topics, / searches (names, then from three characters what the pages say), c copies an example, b bookmarks, Tab jumps to the next letter or section, + opens about and settings, ? shows every key, Esc quits.

## Recipes

Source: https://lore.guhhammer.dev/recipes/add-a-folder-to-the-path

## add a folder to the path

Let the shell find programs in a folder, for good, and reload the settings without logging out.

### Steps
- `echo "$PATH" | tr : '\n'` : the folders searched now, one a line
- `export PATH="$HOME/bin:$PATH"` : add ~/bin for this shell
- `echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc` : add it for good (bash)
- `source ~/.bashrc` : load the change now, without logging out
- `fish_add_path ~/bin` : fish: adds it for good

### Notes
- zsh: ~/.zshrc. Login shells on macOS read ~/.zprofile or ~/.bash_profile.

### See also
- export
- source

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/add-a-user

## add a user

Create an account with a home folder and a password, and let it use sudo
if it should.

### Steps
- `sudo adduser NAME` : create the user, its home folder and its password, asking for each (Debian, Ubuntu)
- `sudo useradd -m -s /bin/bash NAME` : the same on any Linux: a home folder (-m) and bash as its shell
- `sudo passwd NAME` : set its password (needed after useradd)
- `sudo usermod -aG sudo NAME` : let it use sudo; the group is `wheel` on Fedora, RHEL and Arch
- `id NAME` : check its groups
- `sudo -iu NAME` : open a shell as that user, to try it

### Notes
- Keep the `-a` in `usermod -aG`: without it, the user is taken out of every other group.
- A new group takes effect at the user's next login.
- macOS: System Settings, Users & Groups, or `sysadminctl -addUser` (see its manual).

### See also
- adduser
- useradd
- usermod
- passwd

### Categories
users system

Source: https://lore.guhhammer.dev/recipes/add-to-the-end-of-a-file

## add to the end of a file

Add lines to a file without replacing it, also to a file only root can write.

### Steps
- `echo 'new line' >> file.txt` : add a line at the end
- `command >> log.txt 2>&1` : add a command's output and errors
- `command | tee -a log.txt` : see it and add it to the file
- `echo 'new line' | sudo tee -a /etc/some.conf` : add to a file only root can write

### Notes
- One `>` replaces the file; two, `>>`, add to it.
- `sudo echo x >> /etc/file` fails: the redirection is done by your shell, not by sudo.

### See also
- tee
- echo

### Categories
files shell

Source: https://lore.guhhammer.dev/recipes/add-up-numbers-in-a-file

## add up numbers in a file

Sum a column of numbers, from a file or a command's output.

### Steps
- `awk '{s+=$1} END {print s}' numbers.txt` : the sum of the first column
- `awk -F, '{s+=$3} END {print s}' data.csv` : the sum of the third column of a CSV
- `paste -sd+ numbers.txt | bc` : one number a line, added with bc
- `awk '{s+=$1; n++} END {print s/n}' numbers.txt` : the average

### See also
- awk
- paste
- bc

### Categories
text

Source: https://lore.guhhammer.dev/recipes/argument-list-too-long

## argument list too long

"Argument list too long" from rm, cp or mv: too many files for one command line. Hand them over in batches.

### Steps
- `find . -maxdepth 1 -name '*.log' -delete` : delete them without listing them on the command line
- `find . -maxdepth 1 -name '*.jpg' -exec mv -t /dest/ {} +` : move them, many at a time (GNU mv)
- `printf '%s\0' *.log | xargs -0 rm` : xargs makes batches that fit
- `getconf ARG_MAX` : how long a command line can be here

### See also
- find
- xargs
- getconf

### Categories
files shell

Source: https://lore.guhhammer.dev/recipes/ask-for-input-in-a-script

## ask for input in a script

Ask yes or no, read a password without showing it, or wait for an answer with a time limit.

### Steps
- `read -rp 'Continue? [y/N] ' answer` : ask, and keep the answer
- `[[ $answer == [yY]* ]] || exit 1` : stop unless it starts with y
- `read -rsp 'Password: ' password; echo` : read a password without showing it
- `read -rt 10 -p 'Name: ' name || name=guest` : wait 10 seconds at most

### See also
- read

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/back-up-and-restore-postgresql

## back up and restore postgresql

Run a .sql file, dump a PostgreSQL database and load it back, from the terminal.

### Steps
- `sudo -u postgres psql` : connect as the postgres admin ("role does not exist": use this)
- `psql -U NAME -d dbname -f file.sql` : run a .sql file
- `pg_dump -U NAME -d dbname -F c -f db.dump` : dump a database in pg_restore's format
- `pg_restore -U NAME -d dbname db.dump` : load it back
- `pg_dump -U NAME dbname > dump.sql` : a plain .sql dump, loaded with psql -f
- `psql -U NAME -c 'SELECT version();'` : which PostgreSQL this is

### Notes
- A password without typing it: a ~/.pgpass file, or PGPASSWORD for one command.
- `sudo -u postgres createuser --interactive` makes a role for your user.

### See also
- psql
- pg_dump
- pg_restore

### Categories
databases

Source: https://lore.guhhammer.dev/recipes/change-permissions-of-a-folder

## change permissions of a folder and everything in it

Give a folder, its subfolders and its files the permissions or the owner they need, without making them open to everyone.

### Steps
- `ls -ld folder` : see the folder's permissions and owner now
- `chmod -R u+rwX,go+rX folder` : you can read and write everything; others can read, and enter the folders
- `find folder -type d -exec chmod 755 {} +` : folders: rwx for you, r-x for everyone else
- `find folder -type f -exec chmod 644 {} +` : files: rw for you, read-only for everyone else
- `sudo chown -R NAME:GROUP folder` : give the folder and everything in it to another owner
- `chmod +x script.sh` : let a file be run as a program

### Notes
- `chmod -R 777` lets every user change and delete everything: it is almost never the fix.
- Capital `X` in `u+rwX` adds the x only to folders and to files that already had it.

### See also
- chmod
- chown
- find
- ls

### Categories
files security users

Source: https://lore.guhhammer.dev/recipes/check-a-certificate

## check a certificate

See a site's TLS certificate, when it expires and who issued it, or the same for a .pem file.

### Steps
- `openssl s_client -connect example.com:443 -servername example.com < /dev/null | openssl x509 -noout -dates -subject -issuer` : a site's certificate: dates, name, issuer
- `openssl x509 -in cert.pem -noout -enddate` : when a certificate file expires
- `openssl x509 -in cert.pem -noout -text` : everything in it
- `openssl x509 -in cert.pem -noout -checkend 2592000` : does it expire within 30 days? (exit 1 if so)
- `curl -vI https://example.com 2>&1 | grep -E 'expire|issuer'` : the same, the quick way

### See also
- openssl
- curl

### Categories
security network

Source: https://lore.guhhammer.dev/recipes/check-a-files-permissions

## check a file's permissions

See who may read, write and run a file or a folder, and why a path is refused.

### Steps
- `ls -l file.txt` : rwx for the owner, the group and everyone else, then owner and group
- `ls -ld folder` : a folder's own permissions, not its contents
- `stat -c '%a %U:%G %n' file.txt` : the permissions as a number, owner and group (GNU)
- `namei -l /path/to/file.txt` : every folder on the way: one without x refuses the whole path
- `id` : your user and groups, to compare

### Notes
- macOS: `stat -f '%Lp %Su:%Sg %N' file.txt`.

### See also
- ls
- stat
- namei
- id

### Categories
files security

Source: https://lore.guhhammer.dev/recipes/check-if-a-file-or-folder-exists

## check if a file or folder exists

Test in a script whether a path exists, is a file, a folder, empty or runnable.

### Steps
- `[ -f config.txt ] && echo 'it is a file'` : a regular file
- `[ -d logs ] || mkdir logs` : a folder; make it when it is missing
- `[ ! -e path ] && echo 'nothing there'` : nothing at all by that name
- `[ -s data.csv ] && echo 'not empty'` : a file that is not empty
- `[ -x script.sh ] && ./script.sh` : a file you may run
- `[ -L link ] && echo 'a symbolic link'` : a link

### Notes
- Quote paths that may have spaces: `[ -f "$file" ]`.
- In scripts, `if [ -d "$dir" ]; then … fi` does the same over several lines.

### See also
- test

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/check-if-a-program-is-installed

## check if a program is installed

Find whether a command exists, where it is, and which package it came from.

### Steps
- `command -v git` : its path, or nothing if it is not there (use this in scripts)
- `type -a python3` : every python3 the shell can find, aliases and functions too
- `git --version` : its version
- `dpkg -l | grep NAME` : installed by apt? (Debian, Ubuntu)
- `apt policy NAME` : installed and available versions

### Notes
- lore shows every command it finds, and each page's VERSION says the package.

### See also
- command
- type
- dpkg
- apt

### Categories
shell packages

Source: https://lore.guhhammer.dev/recipes/check-if-a-string-contains-a-text

## check if a string contains a text

Test in a script whether a string contains, starts with or matches something.

### Steps
- `[[ $text == *"needle"* ]] && echo found` : contains needle
- `[[ $text == prefix* ]] && echo yes` : starts with prefix
- `[[ $text =~ ^[0-9]+$ ]] && echo 'a number'` : matches a regular expression
- `grep -q 'needle' <<< "$text" && echo found` : with grep, also in sh
- `[[ -z $text ]] && echo empty` : is empty

### Notes
- [[ ]] is bash and zsh; in plain sh use case or grep.

### See also
- grep

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/command-not-found-after-installing

## command not found after installing

You installed a program but the shell says "command not found": find where it went and let the shell see it.

### Steps
- `hash -r` : make the shell forget its old list of commands
- `ls ~/.local/bin ~/.cargo/bin ~/go/bin` : where pip, cargo and go put programs
- `echo "$PATH" | tr : '\n'` : the folders the shell searches
- `exec "$SHELL" -l` : start the shell again, reading the new settings
- `eval "$(/opt/homebrew/bin/brew shellenv)"` : macOS, Homebrew on Apple Silicon: add brew to this shell
- `npm prefix -g` : where npm installs global programs

### Notes
- When the folder is missing from PATH, see "add a folder to the path".

### See also
- hash
- echo
- brew
- npm

### Categories
shell packages

Source: https://lore.guhhammer.dev/recipes/compare-two-folders

## compare two folders

Find which files differ between two folders, or are only in one of them.

### Steps
- `diff -rq dir1 dir2` : the files that differ, and those only in one
- `diff -r dir1 dir2` : the same, with the lines that differ
- `diff -u old.txt new.txt` : two files, the changed lines in context
- `rsync -rcn --out-format='%n' dir1/ dir2/` : what a copy from dir1 would change in dir2, by content

### Notes
- meld, if installed, shows the same side by side.

### See also
- diff
- rsync
- cmp

### Categories
files text

Source: https://lore.guhhammer.dev/recipes/compress-a-folder

## compress a folder

Pack a folder into one compressed file, look inside it, and unpack it
again.

### Steps
- `tar -czf folder.tar.gz folder/` : pack and compress with gzip, fast
- `tar -cJf folder.tar.xz folder/` : with xz: smaller, slower
- `zip -r folder.zip folder/` : a zip, for people on Windows
- `tar -tzf folder.tar.gz` : list what is inside, without unpacking
- `tar -xzf folder.tar.gz` : unpack it here
- `unzip folder.zip` : unpack a zip

### Notes
- `lore explain "tar -czf folder.tar.gz folder/"` says what each letter does.
- GNU tar also does zstd, fast and small: `tar --zstd -cf folder.tar.zst folder/`.

### See also
- tar
- zip
- unzip
- gzip
- xz

### Categories
archives files

Source: https://lore.guhhammer.dev/recipes/copy-a-folder

## copy a folder

Copy a folder with everything inside it, keeping its dates and permissions if needed.

### Steps
- `cp -r src dest` : copy src and everything in it to dest
- `cp -a src dest` : the same, keeping permissions, dates and links
- `rsync -a src/ dest/` : copy what is inside src into dest; again later copies only what changed
- `rsync -a --progress src/ dest/` : with progress, for big copies

### Notes
- With rsync the slash matters: `src/` copies what is inside, `src` makes dest/src.

### See also
- cp
- rsync

### Categories
files

Source: https://lore.guhhammer.dev/recipes/copy-files-to-and-from-a-server

## copy files to and from a server

Copy a file or a whole folder between this machine and another one over ssh.

### Steps
- `scp file.txt NAME@host:/path/` : send a file to the server
- `scp NAME@host:/path/file.txt .` : fetch a file from the server into this folder
- `scp -r NAME@host:/path/folder .` : fetch a whole folder
- `scp -P 2222 file.txt NAME@host:/path/` : when the server's ssh listens on another port
- `rsync -avz --progress folder/ NAME@host:/path/folder/` : send a folder, only what changed, with progress; it can be run again to resume
- `sftp NAME@host` : browse the server and copy with get and put

### Notes
- scp and rsync use the same login as ssh: keys, passwords and ~/.ssh/config hosts all work.

### See also
- scp
- rsync
- sftp
- ssh

### Categories
network files

Source: https://lore.guhhammer.dev/recipes/copy-to-the-clipboard-from-the-terminal

## copy to the clipboard from the terminal

Send a command's output or a file to the clipboard, and paste from it.

### Steps
- `command | xclip -selection clipboard` : copy, on X11 (xclip)
- `xclip -selection clipboard -o` : paste, on X11
- `command | wl-copy` : copy, on Wayland (wl-clipboard)
- `wl-paste` : paste, on Wayland
- `command | pbcopy` : copy, on macOS
- `pbpaste` : paste, on macOS

### Notes
- Over ssh, your terminal can take copies itself: lore's c key does it that way.

### See also
- xclip
- wl-copy
- pbcopy

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/copy-without-some-folders

## copy without some folders

Copy a folder but leave out some of what is inside, like node_modules or .git.

### Steps
- `rsync -av --exclude='node_modules' src/ dest/` : copy src into dest without node_modules
- `rsync -av --exclude={'.git','*.log'} src/ dest/` : without several things
- `rsync -avn --exclude='node_modules' src/ dest/` : only show what would be copied (-n)

### See also
- rsync
- cp

### Categories
files

Source: https://lore.guhhammer.dev/recipes/copy-overwriting-or-not

## copy, overwriting or not

Copy without being asked each time, or without ever replacing a file that is there.

### Steps
- `alias cp` : see whether cp is an alias for cp -i, which asks
- `\cp -f src dest` : copy without the alias, replacing dest
- `cp -n src dest` : never replace a file that is there
- `cp -i src dest` : ask before replacing
- `rsync -a --ignore-existing src/ dest/` : copy a folder, only the files dest does not have
- `cp -u src dest` : replace only when src is newer (GNU)

### See also
- cp
- rsync
- alias

### Categories
files

Source: https://lore.guhhammer.dev/recipes/count-lines-of-code

## count lines of code

How many lines of code a project has, in total and by language.

### Steps
- `cloc .` : lines of code, comments and blanks, by language (cloc)
- `tokei` : the same, faster (tokei)
- `git ls-files | xargs wc -l | tail -1` : the lines of every file git tracks
- `find . -name '*.py' -print0 | xargs -0 wc -l | tail -1` : the lines of every .py file

### See also
- cloc
- tokei
- wc
- git

### Categories
development text

Source: https://lore.guhhammer.dev/recipes/count-lines-words-and-files

## count lines, words and files

Count the lines of a file or of a command's output, the words, and the files in a folder.

### Steps
- `wc -l file.txt` : the lines of a file
- `wc -l *.csv` : the lines of each file, and the total
- `wc -w file.txt` : the words
- `grep -c . file.txt` : the lines that are not empty
- `ls | wc -l` : the files and folders here
- `find . -type f | wc -l` : every file under this folder

### See also
- wc
- grep
- find

### Categories
text files

Source: https://lore.guhhammer.dev/recipes/count-the-processors

## count the processors

How many processors and cores this machine has, and what they are.

### Steps
- `nproc` : the processors programs can use
- `lscpu` : the model, cores, threads and caches
- `grep -c ^processor /proc/cpuinfo` : the same count, from the kernel
- `sysctl -n hw.ncpu` : macOS

### See also
- nproc
- lscpu
- sysctl

### Categories
system hardware

Source: https://lore.guhhammer.dev/recipes/create-a-large-file

## create a large file

Make a file of a given size, for testing disks, uploads or swap.

### Steps
- `fallocate -l 1G big.img` : 1 GB at once, reserved on the disk (Linux)
- `truncate -s 1G sparse.img` : 1 GB that takes no room until written
- `dd if=/dev/zero of=big.img bs=1M count=1024 status=progress` : 1 GB of zeros, written out
- `head -c 100M /dev/urandom > random.bin` : 100 MB of random bytes

### See also
- fallocate
- truncate
- dd

### Categories
files disks

Source: https://lore.guhhammer.dev/recipes/create-an-empty-file

## create an empty file

Make a new empty file, empty an existing one, or make a file with a few lines in it.

### Steps
- `touch file.txt` : make it if it is not there; else just update its date
- `> file.txt` : make it, or empty it if it is there
- `truncate -s 0 file.txt` : empty a file, even one a program has open
- `echo 'one line' > file.txt` : make it with one line in it
- `printf 'line 1\nline 2\n' > file.txt` : with several lines

### See also
- touch
- truncate
- printf

### Categories
files

Source: https://lore.guhhammer.dev/recipes/create-nested-folders

## create nested folders

Make a folder and every folder above it that is missing, and copy a file into a path that does not exist yet.

### Steps
- `mkdir -p a/b/c` : make a, a/b and a/b/c, as needed; no error if they exist
- `mkdir -p "$(dirname dest/sub/file.txt)" && cp file.txt dest/sub/file.txt` : make the folders for a copy, then copy
- `install -D file.txt dest/sub/file.txt` : the same in one step (GNU)
- `cp --parents src/sub/file.txt dest/` : copy keeping the path: dest/src/sub/file.txt (GNU)

### See also
- mkdir
- cp
- install

### Categories
files

Source: https://lore.guhhammer.dev/recipes/dates-and-timestamps

## dates and timestamps

Print dates in any format, turn epoch seconds into dates and back, use other time zones.

### Steps
- `date +%F` : today as 2026-11-23
- `date '+%Y-%m-%d %H:%M:%S'` : date and time
- `date +%s` : seconds since 1970 (epoch)
- `date -d @1700000000` : an epoch time as a date (GNU; macOS: date -r 1700000000)
- `date -d 'yesterday' +%F` : yesterday, next monday, 3 days ago… (GNU)
- `TZ=UTC date` : the time in another zone

### See also
- date

### Categories
shell text

Source: https://lore.guhhammer.dev/recipes/delete-empty-lines

## delete empty lines

Take out the empty lines of a file, also the ones with only spaces.

### Steps
- `sed -i '/^$/d' file.txt` : delete the empty lines
- `sed -i '/^[[:space:]]*$/d' file.txt` : also the lines with only spaces or tabs
- `grep -v '^$' file.txt > new.txt` : write the file without them to a new one
- `awk 'NF' file.txt` : show it without empty or blank lines

### Notes
- macOS: `sed -i ''` in place of `sed -i`.

### See also
- sed
- grep
- awk

### Categories
text

Source: https://lore.guhhammer.dev/recipes/delete-files-and-folders

## delete files and folders

Remove files and folders, ask before each, or remove huge folders quickly.

### Steps
- `rm file.txt` : delete a file
- `rm -ri folder` : delete a folder, asking for each file
- `rm -rf folder` : delete a folder and everything in it, without asking
- `find . -name '*.tmp' -delete` : delete every .tmp file under here
- `gio trash file.txt` : move it to the desktop's trash instead

### Notes
- There is no undo: check the path, mind spaces in names, and never run `rm -rf` with a variable that could be empty.
- "Argument list too long": see the recipe on that, or use find -delete.

### See also
- rm
- find
- gio

### Categories
files

Source: https://lore.guhhammer.dev/recipes/delete-lines-containing-a-text

## delete lines containing a text

Remove every line of a file that contains a word, or keep only those lines.

### Steps
- `grep -v 'text' file.txt > new.txt` : write the file without those lines to a new file
- `sed -i '/text/d' file.txt` : delete them in the file itself
- `sed -i.bak '/text/d' file.txt` : the same, keeping the old file as file.txt.bak
- `grep 'text' file.txt` : the opposite: show only the lines that contain it
- `grep -c 'text' file.txt` : count how many lines contain it

### Notes
- macOS: `sed -i '' '/text/d' file.txt` (its sed needs a value after -i).

### See also
- grep
- sed

### Categories
text files

Source: https://lore.guhhammer.dev/recipes/disk-full-but-df-says-there-is-room

## disk full but df says there is room

"No space left on device" with free gigabytes: the disk is out of inodes, the slots for files. Find the folder with too many small files.

### Steps
- `df -h` : the space left
- `df -i` : the inodes left: IUse% at 100% is the problem
- `sudo du --inodes -xd 1 / | sort -n | tail` : the folders with the most files, at the top of the disk (GNU)
- `sudo find /var -xdev -type f | cut -d/ -f2-4 | sort | uniq -c | sort -n | tail` : where under /var the files are

### Notes
- The usual ones: session or cache folders, mail queues, old kernels' headers. Delete what you know is safe.

### See also
- df
- du
- find

### Categories
disks files

Source: https://lore.guhhammer.dev/recipes/docker-cannot-connect-to-the-daemon

## docker cannot connect to the daemon

"Cannot connect to the Docker daemon" or "permission denied" on docker.sock: start the service, or let your user use it.

### Steps
- `systemctl status docker` : is the service running?
- `sudo systemctl enable --now docker` : start it, and at every boot
- `ls -l /var/run/docker.sock` : who may use the socket: root and the docker group
- `sudo usermod -aG docker $USER` : join the docker group, then log out and in
- `docker info` : check it works

### Notes
- The docker group is as good as root: only add users you trust.
- macOS and Windows: start Docker Desktop.

### See also
- docker
- systemctl
- usermod

### Categories
containers

Source: https://lore.guhhammer.dev/recipes/download-a-whole-folder-from-a-website

## download a whole folder from a website

Fetch every file under a web folder, without climbing to the folders above it.

### Steps
- `wget -r -np -nH -R 'index.html*' https://example.com/files/` : every file under /files/, not the folders above (-np), without index pages
- `wget -m -np https://example.com/docs/` : mirror it, keeping the dates, to update later
- `wget -c https://example.com/big.iso` : a single file, resuming if it was cut
- `wget -i urls.txt` : every address listed in a file

### Notes
- macOS has no wget: `brew install wget`, or `curl -O` for one file.

### See also
- wget
- curl

### Categories
network files

Source: https://lore.guhhammer.dev/recipes/environment-variables

## environment variables

List, read, set and remove environment variables, for a command or for the session.

### Steps
- `printenv | sort` : every variable
- `echo "$HOME"` : one of them
- `export NAME=value` : set one for this shell and what it starts
- `NAME=value command` : set one for one command only
- `unset NAME` : remove one
- `set -a; source .env; set +a` : load a file of NAME=value lines into the shell

### Notes
- To keep a variable, put the export line in ~/.bashrc (or ~/.zshrc).

### See also
- printenv
- export
- env

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/exclude-a-folder-from-find

## exclude a folder from find

Search with find without going into folders like .git or node_modules.

### Steps
- `find . -path ./node_modules -prune -o -name '*.js' -print` : every .js file, without going into node_modules
- `find . -not -path '*/.git/*' -name '*.md'` : every .md file outside .git folders (still walks them)
- `find . \( -name .git -o -name node_modules \) -prune -o -type f -print` : every file, skipping both folders
- `find . -name '*.log' 2>/dev/null` : hide the permission denied messages

### Notes
- `-prune` does not go into the folder at all, so it is fast on big trees; `-not -path` still walks it.

### See also
- find
- fd

### Categories
files search

Source: https://lore.guhhammer.dev/recipes/find-a-file

## find a file

Find a file by its name, by when it changed, or by what is written in it.

### Steps
- `find . -iname '*report*'` : files under this folder with "report" in the name, any case
- `locate -i report` : the same over the whole machine, from an index, at once
- `find . -mtime -1` : files changed in the last day
- `grep -rIl 'some text' .` : files under this folder that contain the text
- `grep -rn 'some text' .` : the lines that contain it, with file and line number
- `rg 'some text'` : the same, faster, with ripgrep

### Notes
- `locate` knows only what was there when its index was last made: `sudo updatedb` makes it again.
- In grep, `-I` skips binary files and `-l` prints only the file names.

### See also
- find
- locate
- grep
- rg
- fd

### Categories
files search

Source: https://lore.guhhammer.dev/recipes/find-a-files-encoding

## find a file's encoding

See which character encoding a text file is in, and convert it to UTF-8.

### Steps
- `file -i file.txt` : the kind of file and its charset (macOS: file -I)
- `iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt` : convert it to UTF-8
- `iconv -l` : the encodings iconv knows
- `uchardet file.txt` : a better guess, if uchardet is installed

### Notes
- No tool can be sure of an encoding: it is a guess from the bytes.

### See also
- file
- iconv

### Categories
text

Source: https://lore.guhhammer.dev/recipes/find-big-files

## find big files

Find the files that take the most room, on a whole disk or in a folder.

### Steps
- `find / -xdev -type f -size +500M 2>/dev/null` : every file over 500 MB on this disk
- `find ~ -type f -size +100M -exec ls -lh {} +` : files over 100 MB in your home, with their sizes
- `du -ah ~ 2>/dev/null | sort -h | tail -20` : the 20 biggest files and folders in your home
- `ls -lhS` : the files in this folder, biggest first

### Notes
- `-xdev` keeps `find` on one disk; `2>/dev/null` hides the folders you may not read.
- `+500M` means more than 500 MB; `k` and `G` work too.

### See also
- find
- du
- ncdu

### Categories
disks files

Source: https://lore.guhhammer.dev/recipes/find-files-containing-a-text

## find files containing a text

Search every file under a folder for a word or a phrase, and show where it is.

### Steps
- `grep -rn 'some text' .` : every line containing the text, under this folder, with file and line number
- `grep -rl 'some text' .` : only the names of the files that contain it
- `grep -rni 'some text' .` : the same, ignoring upper and lower case
- `grep -rnw 'word' .` : only where it is a whole word
- `grep -rn --include='*.py' 'some text' .` : only in the files of one kind
- `grep -rn --exclude-dir={.git,node_modules} 'some text' .` : skipping folders you do not want searched
- `rg 'some text'` : the same, faster, with ripgrep, which skips what .gitignore lists

### Notes
- `-I` skips binary files, and `2>/dev/null` hides the files you may not read.

### See also
- grep
- rg
- find

### Categories
files text search

Source: https://lore.guhhammer.dev/recipes/find-recently-changed-files

## find recently changed files

The newest files in a folder, or those changed in the last minutes or days.

### Steps
- `ls -lt | head` : the newest here, first
- `ls -t | head -1` : only the newest one's name
- `find . -type f -mmin -60` : files changed in the last hour, under here
- `find . -type f -mtime -2` : changed in the last two days
- `find . -type f -printf '%T+ %p\n' | sort | tail -20` : the 20 newest under here, with dates (GNU)

### See also
- ls
- find

### Categories
files

Source: https://lore.guhhammer.dev/recipes/find-the-scripts-own-folder

## find the script's own folder

Inside a script, find the folder the script is in, to reach files next to it.

### Steps
- `dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` : the script's folder, as a full path
- `cd "$dir"` : work from there
- `echo "$(basename "$0")"` : the script's own name
- `realpath "$0"` : its full path, links resolved

### See also
- dirname
- realpath

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/find-this-machines-ip-address

## find this machine's ip address

This machine's address on the local network, and the one the internet sees.

### Steps
- `ip -br addr` : every interface and its addresses (Linux)
- `hostname -I` : the addresses only (Linux)
- `ip route get 1.1.1.1` : the address used to go out: after src
- `curl -s https://ifconfig.me` : the public address the internet sees
- `ipconfig getifaddr en0` : macOS, Wi-Fi or the first network port

### See also
- ip
- hostname
- curl

### Categories
network

Source: https://lore.guhhammer.dev/recipes/find-what-killed-a-process

## find what killed a process

A program vanished or says "Killed": usually the kernel ran out of memory and stopped it. Find out.

### Steps
- `sudo dmesg -T | grep -i -E 'killed process|out of memory'` : the kernel's out-of-memory kills, with times
- `journalctl -k | grep -i oom` : the same from the journal
- `journalctl -u NAME --since today` : a service's own last words
- `echo $?` : right after it ended: 137 means killed by force (128 + 9), 143 asked to stop
- `free -h` : how much memory and swap there is

### See also
- dmesg
- journalctl
- free

### Categories
processes system

Source: https://lore.guhhammer.dev/recipes/fix-error-while-loading-shared-libraries

## fix error while loading shared libraries

"cannot open shared object file": a program needs a library that is missing or not where it looks.

### Steps
- `ldd /path/to/program` : every library it needs; the missing ones say "not found"
- `ldconfig -p | grep libNAME` : is the library known to the system?
- `apt-file search libNAME.so.1` : the package that has it (Debian, Ubuntu; dnf provides on Fedora)
- `sudo ldconfig` : after installing a library in /usr/local/lib, let the system find it
- `LD_LIBRARY_PATH=/opt/app/lib /path/to/program` : run it with an extra folder to look in

### See also
- ldd
- ldconfig
- apt-file

### Categories
development packages

Source: https://lore.guhhammer.dev/recipes/fix-windows-line-endings

## fix windows line endings

"bad interpreter: ^M" and odd characters: the file has Windows line endings (CRLF). Find them and change them to Unix ones (LF).

### Steps
- `file script.sh` : says "with CRLF line terminators" when it has them
- `cat -A script.sh | head` : shows them as ^M$ at the ends of the lines
- `dos2unix script.sh` : change them, if dos2unix is installed
- `sed -i 's/\r$//' script.sh` : the same with sed
- `unix2dos file.txt` : the other way, for Windows

### Notes
- git can do it for you: `git config --global core.autocrlf input`.

### See also
- dos2unix
- file
- sed

### Categories
text development

Source: https://lore.guhhammer.dev/recipes/free-disk-space

## free disk space

Find what fills a disk, then clear what is safe to clear: old package
files, logs, caches.

### Steps
- `df -h` : see how full each disk is, and which one is short of space
- `du -xh -d 1 / 2>/dev/null | sort -h` : the biggest folders at the top of that disk, biggest last
- `ncdu -x /` : walk through the folders by size and delete from there, if ncdu is installed
- `sudo journalctl --vacuum-size=200M` : shrink the system's logs to 200 MB
- `sudo apt clean` : remove the downloaded package files (Debian, Ubuntu)
- `sudo apt autoremove` : remove the packages nothing needs any more (Debian, Ubuntu)
- `rm -rf ~/.cache/thumbnails` : delete the cached thumbnails, made again when needed

### Notes
- Fedora and RHEL: `sudo dnf clean all` and `sudo dnf autoremove`. Arch: `sudo pacman -Sc`.
- `-x` keeps `du` and `ncdu` on that one disk, so other disks and network folders are not counted.
- macOS: the same `df -h` and `du -xh -d 1 /`; Homebrew's downloads go with `brew cleanup`.

### See also
- df
- du
- ncdu
- journalctl

### Categories
disks files system

Source: https://lore.guhhammer.dev/recipes/get-a-files-name-folder-and-extension

## get a file's name, folder and extension

Take a path apart in a script: the folder, the name, the name without its extension, the extension.

### Steps
- `file="${path##*/}"` : the name: /a/b/report.tar.gz → report.tar.gz
- `dir="${path%/*}"` : the folder: /a/b
- `ext="${file##*.}"` : the last extension: gz
- `base="${file%.*}"` : the name without it: report.tar
- `basename "$path" .gz` : the same with basename, ending removed
- `dirname "$path"` : the folder, with dirname

### Notes
- ## and %% take the longest match, # and % the shortest: ${file%%.*} gives report.

### See also
- basename
- dirname

### Categories
shell files development

Source: https://lore.guhhammer.dev/recipes/get-inside-a-docker-container

## get inside a docker container

Open a shell in a running container, copy files in and out, read its logs, share a folder with it.

### Steps
- `docker ps` : the running containers and their names
- `docker exec -it NAME sh` : a shell inside it (bash, if the image has it)
- `docker logs -f NAME` : its output, as it comes
- `docker cp NAME:/path/file ./` : copy a file out of it
- `docker run -it --rm -v "$PWD":/work -w /work ubuntu bash` : a new container with this folder inside it
- `docker compose exec SERVICE sh` : with Compose, by service name

### See also
- docker

### Categories
containers

Source: https://lore.guhhammer.dev/recipes/get-the-full-path-of-a-file

## get the full path of a file

Turn a file's name into its whole path from /, through links if you want.

### Steps
- `realpath file.txt` : its absolute path, links resolved
- `readlink -f file.txt` : the same, on older systems
- `echo "$PWD/file.txt"` : this folder's path plus the name
- `find "$PWD" -name '*.txt'` : every .txt file under here, with full paths
- `pwd` : the folder you are in

### See also
- realpath
- readlink
- pwd

### Categories
files

Source: https://lore.guhhammer.dev/recipes/import-and-export-a-mysql-database

## import and export a mysql database

Load a .sql file into MySQL or MariaDB, dump a database to one, and connect from the terminal.

### Steps
- `mysql -u NAME -p` : connect; it asks for the password
- `mysql -u NAME -p dbname < dump.sql` : load a .sql file into a database
- `mysqldump -u NAME -p dbname > dump.sql` : dump a database to a file
- `mysqldump -u NAME -p --all-databases > all.sql` : every database
- `gunzip < dump.sql.gz | mysql -u NAME -p dbname` : load a compressed dump
- `mysql -u NAME -p -e 'SHOW DATABASES;'` : run one query and quit

### Notes
- -h host connects to another machine; -P to another port.

### See also
- mysql
- mysqldump

### Categories
databases

Source: https://lore.guhhammer.dev/recipes/keep-a-command-running-after-logout

## keep a command running after logout

Start a long job so it survives closing the terminal or the ssh session, and come back to it.

### Steps
- `nohup long-command > out.log 2>&1 &` : start it in the background, immune to the hang-up
- `tmux new -s work` : or start it inside a tmux session; Ctrl+B then D leaves it running
- `tmux attach -t work` : come back to it later, even from another ssh login
- `screen -S work` : the same with screen; Ctrl+A then D leaves it
- `screen -r work` : come back to the screen session
- `disown -h %1` : already running? Ctrl+Z, then bg, then this, and it survives logout

### See also
- nohup
- tmux
- screen
- disown

### Categories
processes shell

Source: https://lore.guhhammer.dev/recipes/list-and-close-tmux-or-screen-sessions

## list and close tmux or screen sessions

See the terminal sessions left running, join one, or end them.

### Steps
- `tmux ls` : the tmux sessions
- `tmux attach -t NAME` : join one
- `tmux kill-session -t NAME` : end one
- `screen -ls` : the screen sessions
- `screen -r NAME` : join one
- `screen -X -S NAME quit` : end one, from outside

### See also
- tmux
- screen

### Categories
processes shell

Source: https://lore.guhhammer.dev/recipes/list-only-folders

## list only folders

List the folders here and not the files, or only the files.

### Steps
- `ls -d */` : the folders here
- `find . -maxdepth 1 -type d` : the same, hidden ones too
- `find . -maxdepth 1 -type f` : only the files
- `tree -d -L 2` : the folders two levels down, as a tree

### See also
- ls
- find
- tree

### Categories
files

Source: https://lore.guhhammer.dev/recipes/list-users-and-groups

## list users and groups

See the accounts on this machine, the groups, and who is in each.

### Steps
- `getent passwd | cut -d: -f1` : every account's name
- `getent passwd | awk -F: '$3 >= 1000 {print $1}'` : the people, not the system accounts (Linux)
- `getent group` : every group and its members
- `groups NAME` : the groups of one user
- `id` : your own user, groups and numbers
- `dscl . list /Users` : macOS

### See also
- getent
- groups
- id

### Categories
users system

Source: https://lore.guhhammer.dev/recipes/loop-over-files-numbers-and-lists

## loop over files, numbers and lists

Repeat commands for every file of a kind, a range of numbers, or the items of an array.

### Steps
- `for f in *.jpg; do echo "$f"; done` : every .jpg here
- `for i in {1..10}; do echo "$i"; done` : 1 to 10
- `for ((i = 0; i < n; i++)); do echo "$i"; done` : a range in variables
- `for x in "${list[@]}"; do echo "$x"; done` : every item of an array
- `find . -name '*.log' -print0 | while IFS= read -r -d '' f; do gzip "$f"; done` : every file under here, any name
- `seq 1 2 10` : 1, 3, 5, 7, 9: numbers for other commands

### Notes
- {1..$n} does not work: braces come before variables; use the (( )) form.

### See also
- seq
- find

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/make-a-script-take-options

## make a script take options

Read a script's arguments and options, and stop with a usage line when they are wrong.

### Steps
- `echo "$1 $2 ($# arguments)"` : the first two arguments, and how many there are
- `[ $# -eq 0 ] && { echo "usage: $0 FILE"; exit 1; }` : stop when none were given
- `for arg in "$@"; do echo "$arg"; done` : go through every argument, spaces kept
- `while getopts 'vf:' opt; do case $opt in v) verbose=1;; f) file=$OPTARG;; *) exit 1;; esac; done` : -v and -f FILE options
- `shift $((OPTIND - 1))` : after getopts: what is left are the plain arguments
- `name="${1:-world}"` : a default when no argument was given

### See also
- getopts
- shift

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/make-a-symbolic-link

## make a symbolic link

Make a name that points to another file or folder, see where a link points, and change or remove it.

### Steps
- `ln -s /path/to/target linkname` : make linkname point to the target
- `ls -l linkname` : see where it points
- `readlink -f linkname` : the full path it ends up at, through every link
- `ln -sfn /path/to/other linkname` : point an existing link somewhere else
- `rm linkname` : remove the link; the target stays
- `ln /path/to/file hardlink` : a hard link instead: another name for the same file, same disk only

### Notes
- Remove a link to a folder with `rm linkname`, without a slash at the end: `rm -r linkname/` would delete what is inside the target.
- A relative target is taken from where the link is, not from where you are.

### See also
- ln
- readlink
- ls

### Categories
files

Source: https://lore.guhhammer.dev/recipes/make-web-requests-with-curl

## make web requests with curl

Send GET and POST requests, JSON and files, see headers and status codes, go through a proxy.

### Steps
- `curl -sS https://example.com` : a page, without the progress bar, errors still shown
- `curl -I https://example.com` : only the headers
- `curl -s -o /dev/null -w '%{http_code}\n' https://example.com` : only the status code
- `curl -X POST -H 'Content-Type: application/json' -d '{"name":"x"}' https://api.example.com/items` : post JSON
- `curl -F 'file=@photo.jpg' https://example.com/upload` : upload a file as a form
- `curl -u NAME:password https://example.com` : with a user and password
- `curl -x http://proxy:8080 https://example.com` : through a proxy
- `curl -L -o file.zip https://example.com/file.zip` : download, following redirects

### Notes
- -v shows everything sent and received, to find out why a request fails.

### See also
- curl
- wget

### Categories
network development

Source: https://lore.guhhammer.dev/recipes/merge-pdf-files

## merge pdf files

Join several PDF files into one, and take pages out of one.

### Steps
- `pdfunite a.pdf b.pdf c.pdf all.pdf` : join them in that order (poppler-utils)
- `qpdf --empty --pages a.pdf b.pdf -- all.pdf` : the same with qpdf
- `qpdf in.pdf --pages . 1-3 -- first.pdf` : keep only pages 1 to 3
- `gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=all.pdf a.pdf b.pdf` : with Ghostscript, which also shrinks them

### See also
- pdfunite
- qpdf
- gs

### Categories
files

Source: https://lore.guhhammer.dev/recipes/pack-a-folder-without-some-files

## pack a folder without some files

Make a tar archive of a folder, leaving out folders like node_modules and files like logs.

### Steps
- `tar -czf project.tar.gz --exclude='node_modules' --exclude='*.log' project/` : pack project without node_modules and the logs
- `tar -czf project.tar.gz --exclude-vcs project/` : without .git and the like (GNU tar)
- `tar -tzf project.tar.gz | less` : check what went in
- `git archive -o project.tar.gz HEAD` : in a git repository: only the files git tracks

### Notes
- Put the --exclude options before the folder: some tar versions ignore them after it.

### See also
- tar
- git

### Categories
archives files

Source: https://lore.guhhammer.dev/recipes/pretty-print-json

## pretty-print json

Show JSON indented and coloured, pick values out of it, from a file or a web request.

### Steps
- `jq . file.json` : the file, indented and coloured
- `curl -s https://api.example.com/items | jq .` : a web answer, the same way
- `jq '.items[0].name' file.json` : one value out of it
- `jq -r '.items[].name' file.json` : a value from every item, as plain text
- `python3 -m json.tool file.json` : without jq: indented by Python

### Notes
- jq is a package of its own on most systems: `sudo apt install jq`, `brew install jq`.

### See also
- jq
- curl
- python3

### Categories
text development

Source: https://lore.guhhammer.dev/recipes/print-colors-and-new-lines

## print colors and new lines

Print text in color, and print new lines from a string, which plain echo may not do.

### Steps
- `printf 'one\ntwo\n'` : new lines, the same in every shell
- `echo -e 'one\ntwo'` : the same with bash's echo
- `printf '\033[31mred\033[0m\n'` : red text, then back to normal
- `printf '\033[1;32mOK\033[0m\n'` : bold green
- `echo "$(tput setaf 4)blue$(tput sgr0)"` : colors by name of the terminal's capability

### Notes
- Colors 30 to 37: black, red, green, yellow, blue, magenta, cyan, white; 1; makes them bold.

### See also
- printf
- tput

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/print-or-remove-lines-of-a-file

## print or remove lines of a file

Show one line by its number, a range, skip the first ones, or take off the last.

### Steps
- `sed -n '5p' file.txt` : line 5
- `sed -n '5,10p' file.txt` : lines 5 to 10
- `tail -n +2 file.txt` : everything from line 2: skip a header
- `head -n 20 file.txt` : the first 20 lines
- `tail -n 20 file.txt` : the last 20 lines
- `sed -i '$d' file.txt` : remove the last line
- `head -n -5 file.txt` : everything but the last 5 lines (GNU)

### See also
- sed
- head
- tail
- awk

### Categories
text

Source: https://lore.guhhammer.dev/recipes/read-a-file-line-by-line

## read a file line by line

Go through a file's lines in a script, also split into fields, without losing spaces or backslashes.

### Steps
- `while IFS= read -r line; do echo "$line"; done < file.txt` : each line as it is
- `while IFS=, read -r name age; do echo "$name is $age"; done < people.csv` : each line split at the commas
- `command | while IFS= read -r line; do echo "$line"; done` : each line of a command's output
- `mapfile -t lines < file.txt` : every line into an array at once (bash 4)

### Notes
- `for line in $(cat file)` splits at every space, not at lines: use while read.
- A last line without a newline is skipped by read: `|| [ -n "$line" ]` keeps it.

### See also
- read
- mapfile

### Categories
shell text development

Source: https://lore.guhhammer.dev/recipes/read-the-system-logs

## read the system logs

Find what went wrong: the errors since boot, a service's log, the kernel's messages.

### Steps
- `journalctl -b -p err` : every error since this boot
- `journalctl -xe` : the latest entries, explained
- `journalctl --since '1 hour ago'` : the last hour
- `journalctl -u NAME` : one service's log
- `sudo dmesg -T | tail -50` : the kernel's latest messages: disks, USB, drivers
- `journalctl -b -1 -p err` : the errors of the boot before, after a crash

### Notes
- Without systemd's journal: /var/log/syslog or /var/log/messages.

### See also
- journalctl
- dmesg

### Categories
system services

Source: https://lore.guhhammer.dev/recipes/rename-many-files

## rename many files

Change the ending of many files, replace spaces in names, or number them.

### Steps
- `for f in *.txt; do mv -- "$f" "${f%.txt}.md"; done` : every .txt to .md
- `rename 's/\.txt$/.md/' *.txt` : the same with rename (the perl one; package rename)
- `for f in *\ *; do mv -- "$f" "${f// /_}"; done` : spaces in names to underscores
- `rename -n 's/ /_/g' *` : show what rename would do, without doing it

### Notes
- There are two rename programs: the perl one takes s/old/new/, util-linux's takes old new files.

### See also
- mv
- rename

### Categories
files shell

Source: https://lore.guhhammer.dev/recipes/replace-text-in-a-file

## replace text in a file

Change every place a word or a phrase appears in a file, keeping a copy if you like.

### Steps
- `sed 's/old/new/g' file.txt` : show the file with every old turned into new, without changing it
- `sed -i 's/old/new/g' file.txt` : change the file itself
- `sed -i.bak 's/old/new/g' file.txt` : the same, keeping the old one as file.txt.bak
- `sed -i '0,/old/s//new/' file.txt` : only the first one in the file (GNU sed)
- `sed -i 's|/old/path|/new/path|g' file.txt` : text with slashes: another separator

### Notes
- macOS: `sed -i '' 's/old/new/g' file.txt`.
- `sed 's/…/…/' file > file` empties the file: write to a new one, or use -i.

### See also
- sed
- perl

### Categories
text files

Source: https://lore.guhhammer.dev/recipes/replace-text-in-many-files

## replace text in many files

Change a word or a phrase in every file under a folder that contains it.

### Steps
- `grep -rl 'old' .` : first, see which files contain it
- `grep -rl 'old' . | xargs sed -i 's/old/new/g'` : change it in all of them
- `find . -name '*.txt' -exec sed -i 's/old/new/g' {} +` : only in the .txt files
- `git diff` : in a git repository, check what changed

### Notes
- Run it in a git repository or on a copy: a wrong pattern changes many files at once.
- macOS: `sed -i ''` in place of `sed -i`.

### See also
- grep
- sed
- find
- xargs

### Categories
text files

Source: https://lore.guhhammer.dev/recipes/run-a-script

## run a script

Make a script runnable and run it, or run it in the shell you are in.

### Steps
- `chmod +x script.sh` : let it be run
- `./script.sh` : run it from its folder
- `bash script.sh` : run it with bash, even without the x
- `head -1 script.sh` : its first line, #!/usr/bin/env bash, says what runs it
- `source script.sh` : run it in this shell, so its cd and variables stay

### Notes
- "bad interpreter" with ^M: see "fix windows line endings".

### See also
- chmod
- bash
- source

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/run-commands-on-a-server-over-ssh

## run commands on a server over ssh

Run one command or a whole local script on another machine, without logging in by hand.

### Steps
- `ssh NAME@host 'uptime'` : one command; its output comes back here
- `ssh NAME@host 'cd /app && git pull && sudo systemctl restart app'` : several, in order
- `ssh NAME@host 'bash -s' < local-script.sh` : run a script from this machine there
- `ssh -t NAME@host 'sudo systemctl restart app'` : one that asks for a password (-t gives it a terminal)
- `ssh NAME@host 'cat /var/log/app.log' > app.log` : bring a file's text back

### See also
- ssh

### Categories
network

Source: https://lore.guhhammer.dev/recipes/save-a-commands-output-in-a-variable

## save a command's output in a variable

Keep what a command prints in a variable, or each line in an array, to use later in a script.

### Steps
- `today=$(date +%F)` : the output of date in today
- `count=$(ls | wc -l)` : a count
- `echo "$today"` : use it; the quotes keep spaces and lines as they are
- `mapfile -t lines < <(git branch)` : each line of the output in an array (bash 4)
- `if out=$(command 2>&1); then echo ok; else echo "failed: $out"; fi` : the output and whether it worked

### Notes
- $(…) is the modern form of backticks: it nests and reads better.

### See also
- mapfile

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/schedule-a-command-with-cron

## schedule a command with cron

Run a command every day, every hour or every few minutes, and see what is scheduled.

### Steps
- `crontab -e` : edit your schedule; a line is minute hour day month weekday command
- `crontab -l` : show your schedule
- `sudo crontab -u NAME -l` : another user's
- `ls /etc/cron.d /etc/cron.daily /etc/cron.hourly` : the system's scheduled jobs
- `systemctl list-timers` : systemd's timers, the other kind of schedule
- `grep CRON /var/log/syslog` : check that a job ran (Debian, Ubuntu)

### Notes
- `*/5 * * * * /home/me/backup.sh` runs every 5 minutes; `0 3 * * * …` every day at 3:00.
- cron sees a new crontab by itself: no restart needed.
- cron runs with almost no PATH: write full paths, and send the output to a file to see errors.

### See also
- crontab
- systemctl

### Categories
system services

Source: https://lore.guhhammer.dev/recipes/search-but-skip-some-files

## search but skip some files

grep through a project without its build folders, minified files or logs.

### Steps
- `grep -rn --exclude-dir={.git,node_modules,dist} 'text' .` : skip those folders
- `grep -rn --include='*.js' --include='*.ts' 'text' .` : only those kinds of files
- `grep -rn --exclude='*.min.js' 'text' .` : skip files by name
- `rg 'text' -g '!*.min.js'` : ripgrep: skips .gitignore's files already; -g adds more

### See also
- grep
- rg

### Categories
text search

Source: https://lore.guhhammer.dev/recipes/see-a-programs-memory-use

## see a program's memory use

How much memory a program really uses, and which programs use the most.

### Steps
- `ps aux --sort=-rss | head` : the programs using the most memory, first (Linux)
- `ps -o pid,rss,vsz,cmd -p PID` : one program: RSS is the memory it really holds, in KB
- `grep -E 'VmRSS|VmSwap' /proc/PID/status` : its memory and its swap (Linux)
- `pmap -x PID | tail -1` : the total of every part of its memory
- `smem -k -P NAME` : memory shared counted fairly, by name (smem)
- `free -h` : the whole machine's memory

### Notes
- Put the program's number in place of PID: `pgrep -l NAME` finds it.
- macOS: `ps -o pid,rss,command -p PID` and Activity Monitor.

### See also
- ps
- pmap
- free
- top

### Categories
processes system

Source: https://lore.guhhammer.dev/recipes/see-each-command-a-script-runs

## see each command a script runs

Debug a script: print every command as it runs, check its syntax, find common mistakes.

### Steps
- `bash -x script.sh` : run it, printing each command first
- `set -x` : inside the script: print from here on; set +x stops
- `bash -n script.sh` : check the syntax without running it
- `shellcheck script.sh` : the usual mistakes, with how to fix them (shellcheck)

### See also
- bash
- shellcheck

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/see-the-size-of-files-and-folders

## see the size of files and folders

How much room each file and folder takes, here or anywhere, biggest last.

### Steps
- `du -sh *` : the size of each file and folder here
- `du -sh .[!.]* *` : the same, hidden ones included
- `du -h -d 1 | sort -h` : the folders here, sorted by size, biggest last
- `du -sh folder` : the total size of one folder
- `ls -lhS` : the files here, biggest first
- `ncdu` : browse sizes folder by folder, if ncdu is installed

### See also
- du
- ncdu
- ls
- df

### Categories
disks files

Source: https://lore.guhhammer.dev/recipes/send-output-and-errors-to-a-file

## send output and errors to a file

Keep what a command prints, its errors too, in a file, or throw them away.

### Steps
- `command > out.log 2>&1` : the output and the errors into out.log (2>&1: errors go where the output goes)
- `command >> out.log 2>&1` : the same, added at the end of the file
- `command 2> errors.log` : only the errors into a file
- `command 2>/dev/null` : throw the errors away
- `command > /dev/null 2>&1` : throw everything away
- `command 2>&1 | tee out.log` : see everything and keep a copy

### Notes
- The order matters: `> out.log 2>&1` works, `2>&1 > out.log` sends the errors to the screen.
- `lore explain "command > out.log 2>&1"` says what each part does.

### See also
- tee

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/set-up-an-ssh-key

## set up an ssh key

Make a key, put it on a server to log in without a password, use a given key, change its passphrase.

### Steps
- `ssh-keygen -t ed25519` : make a key pair in ~/.ssh; the passphrase protects it
- `ssh-copy-id NAME@host` : put the public key on the server
- `ssh -i ~/.ssh/work_key NAME@host` : log in with a given key
- `ssh-keygen -p -f ~/.ssh/id_ed25519` : change or remove its passphrase
- `GIT_SSH_COMMAND='ssh -i ~/.ssh/work_key' git clone git@github.com:org/repo.git` : use a given key for git
- `chmod 600 ~/.ssh/id_ed25519` : "permissions too open": only you may read a private key

### Notes
- Hosts and keys can go in ~/.ssh/config: Host work, HostName, User, IdentityFile.
- Share only the .pub file; the other one stays on your machine.

### See also
- ssh-keygen
- ssh-copy-id
- ssh

### Categories
network security

Source: https://lore.guhhammer.dev/recipes/show-a-folder-tree

## show a folder tree

Show folders and files as a tree, to see how a project is laid out.

### Steps
- `tree` : everything under here, as a tree
- `tree -L 2` : two levels down
- `tree -d` : folders only
- `tree -a -I 'node_modules|.git'` : hidden ones too, without those folders
- `find . -maxdepth 2 | sort` : without tree

### See also
- tree
- find

### Categories
files

Source: https://lore.guhhammer.dev/recipes/sort-and-remove-duplicate-lines

## sort and remove duplicate lines

Sort lines, keep each once, count how often each appears.

### Steps
- `sort file.txt` : sort the lines
- `sort -u file.txt` : sort them and keep each once
- `sort file.txt | uniq -c | sort -rn` : how often each line appears, most first
- `awk '!seen[$0]++' file.txt` : keep each once, in their order
- `sort -t, -k3 -n data.csv` : sort a CSV by its third column, as numbers
- `sort -h sizes.txt` : sort sizes like 2K, 1M, 3G

### Notes
- uniq only removes repeats next to each other: sort first.

### See also
- sort
- uniq
- awk

### Categories
text

Source: https://lore.guhhammer.dev/recipes/split-a-big-file

## split a big file

Cut a big file into smaller pieces, by lines or by size, and join them again.

### Steps
- `split -l 1000 big.txt part_` : pieces of 1,000 lines: part_aa, part_ab…
- `split -b 100M big.bin part_` : pieces of 100 MB
- `split -n 4 big.txt part_` : four pieces of equal size (GNU)
- `split -d -l 1000 --additional-suffix=.csv big.csv part_` : numbered pieces that keep the .csv ending (GNU)
- `cat part_* > big.txt` : join them again

### Notes
- A CSV's header line goes only into the first piece.

### See also
- split
- cat
- csplit

### Categories
files text

Source: https://lore.guhhammer.dev/recipes/split-a-string-in-bash

## split a string in bash

Cut a string at a delimiter into parts or an array.

### Steps
- `IFS=, read -r a b c <<< "x,y,z"` : three parts into three variables
- `IFS=, read -ra parts <<< "$line"` : every part into an array
- `echo "${parts[1]}"` : the second part (arrays start at 0)
- `cut -d, -f2 <<< "$line"` : only the second field, with cut
- `tr ',' '\n' <<< "$line"` : one part a line

### See also
- read
- cut
- tr

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/stop-a-frozen-program

## stop a frozen program

Find a program that stopped answering and end it: politely first, by force
if it must.

### Steps
- `pgrep -l NAME` : the PIDs of the programs with that name
- `kill PID` : ask it to quit, so it can save and clean up
- `kill -9 PID` : force it to stop at once, if it did not quit
- `pkill NAME` : ask every program with that name to quit
- `xkill` : click a window to close its program (X11 desktops)

### Notes
- Put the program's name in place of NAME, and the number from pgrep in place of PID.
- A force-stopped program loses what it had not saved.
- If the whole desktop is frozen on Linux, Ctrl+Alt+F3 often opens a text console where you can log in and do the same.
- macOS: Option+Command+Esc, or the same commands.

### See also
- kill
- pkill
- pgrep
- killall

### Categories
processes

Source: https://lore.guhhammer.dev/recipes/stop-a-script-on-errors

## stop a script on errors

Make a script stop at the first failing command, say where, and still allow the ones that may fail.

### Steps
- `set -euo pipefail` : at the top: stop on errors (-e), on unset variables (-u), on failing pipes
- `trap 'echo "failed at line $LINENO"' ERR` : say where it stopped
- `command || { echo 'command failed'; exit 1; }` : stop with a message of your own
- `command || true` : let this one fail
- `if command; then echo ok; fi` : test whether it worked: $? is its exit code

### See also
- set
- trap

### Categories
shell development

Source: https://lore.guhhammer.dev/recipes/sync-two-folders

## sync two folders

Make one folder a copy of another, here or on a server, copying only what changed.

### Steps
- `rsync -avn --delete src/ dest/` : show what would change, without changing anything
- `rsync -av --delete src/ dest/` : make dest the same as src, deleting what src does not have
- `rsync -avz src/ NAME@host:/backup/src/` : to a server, compressed on the way
- `rsync -av --progress src/ dest/` : copy only, deleting nothing, with progress

### Notes
- --delete removes files from dest: run the -n line first.

### See also
- rsync

### Categories
files network

Source: https://lore.guhhammer.dev/recipes/the-internet-does-not-work

## the internet does not work

Go step by step from this machine out: its address, the router, the
internet by number, then by name.

### Steps
- `ip -br addr` : the network interfaces and their addresses; one should be UP with an address (Linux)
- `ip route` : the default route, through the router
- `ping -c 3 1.1.1.1` : reach the internet by number
- `ping -c 3 example.com` : reach it by name, which needs DNS
- `resolvectl status` : the DNS servers in use (systemd; else read /etc/resolv.conf)
- `curl -I https://example.com` : a whole web request, with the answer's headers
- `tracepath 1.1.1.1` : where on the way the packets stop

### Notes
- Numbers work but names do not: DNS is the problem.
- No default route, or no address: the problem is the cable, the Wi-Fi or DHCP, before the internet.
- macOS: `ifconfig`, `netstat -rn` for the route, `scutil --dns` for DNS, and `traceroute`.

### See also
- ip
- ping
- curl
- tracepath

### Categories
network

Source: https://lore.guhhammer.dev/recipes/time-a-command

## time a command

How long a command takes, and how much memory and processor it used.

### Steps
- `time command` : real is the clock time; user and sys, the processor's
- `/usr/bin/time -v command` : also its peak memory (GNU time)
- `hyperfine 'command'` : run it many times for a fair figure (hyperfine)

### Notes
- real much bigger than user + sys means it was waiting: the disk, the network or you.

### See also
- time
- hyperfine

### Categories
development processes

Source: https://lore.guhhammer.dev/recipes/undo-changes-in-git

## undo changes in git

Throw away changes not committed yet, unstage files, or put work aside for later.

### Steps
- `git status` : what changed, staged or not
- `git restore file.txt` : throw away one file's changes
- `git restore --staged file.txt` : unstage it, keeping the changes
- `git stash` : put every change aside; git stash pop brings them back
- `git clean -nd` : list the new files git does not track
- `git clean -fd` : delete them
- `git reset --hard` : throw away every change to tracked files

### Notes
- restore, clean -fd and reset --hard cannot be undone for changes never committed.

### See also
- git

### Categories
version-control

Source: https://lore.guhhammer.dev/recipes/undo-the-last-git-commit

## undo the last git commit

Take back a commit, keep its changes or not, fix its message, or undo one already pushed.

### Steps
- `git reset --soft HEAD~1` : undo it, keeping its changes staged
- `git reset HEAD~1` : undo it, keeping the changes, unstaged
- `git commit --amend` : change its message, or add what you forgot (git add first)
- `git revert HEAD` : already pushed: a new commit that undoes it
- `git reflog` : every place HEAD was: find a commit you lost

### Notes
- Do not reset or amend commits others already pulled; revert them.

### See also
- git

### Categories
version-control

Source: https://lore.guhhammer.dev/recipes/unmount-a-busy-drive

## unmount a busy drive

"target is busy": something still uses the drive. Find it, stop it, then unmount.

### Steps
- `sudo lsof +f -- /mnt/point` : the open files on it, and their programs
- `sudo fuser -vm /mnt/point` : the programs using it
- `cd ~` : your own shell may be the one inside it
- `sudo umount /mnt/point` : unmount it
- `sudo umount -l /mnt/point` : lazy: detach it now, finish when nothing uses it

### See also
- lsof
- fuser
- umount

### Categories
disks

Source: https://lore.guhhammer.dev/recipes/unpack-an-archive

## unpack an archive

Open any common archive: tar, zip, gz, xz, 7z, rar.

### Steps
- `tar -xf archive.tar.gz` : any tar: .tar, .tar.gz, .tgz, .tar.xz, .tar.zst
- `tar -xf archive.tar.gz -C /dest` : into another folder
- `unzip archive.zip -d folder` : a zip, into a folder
- `gunzip file.gz` : a single .gz file
- `xz -d file.xz` : a single .xz file
- `7z x archive.7z` : 7z, and most other kinds (p7zip)
- `unrar x archive.rar` : rar, if unrar is installed

### Notes
- `tar -tf` and `unzip -l` list what is inside first.

### See also
- tar
- unzip
- 7z
- gunzip

### Categories
archives files

Source: https://lore.guhhammer.dev/recipes/what-is-slowing-the-machine

## what is slowing the machine

See whether the processor, the memory or a disk is the bottleneck, and
which program is behind it.

### Steps
- `uptime` : the load over 1, 5 and 15 minutes; compare it with the number of processors (`nproc`)
- `top` : the busiest programs, live; on Linux, P sorts by processor and M by memory
- `ps aux --sort=-%cpu | head` : the 10 programs using the most processor (Linux)
- `ps aux --sort=-%mem | head` : the 10 using the most memory (Linux)
- `free -h` : memory and swap in use; a full swap slows everything
- `vmstat 1 5` : processor, memory, swap and disk waits, every second, five times
- `df -h` : a full disk slows programs that write to it

### Notes
- A load well above the number of processors means programs are waiting their turn.
- A high `wa` in `vmstat` or `top` means waiting for a disk: `iostat -x 1` (from sysstat) shows which one.
- macOS: `top -o cpu`, `top -o mem`, and `vm_stat` for memory.

### See also
- top
- htop
- ps
- vmstat
- free

### Categories
processes system

Source: https://lore.guhhammer.dev/recipes/what-is-using-a-port

## what is using a port

Find the program listening on a port (port 80 here), see what it is, and
stop it if it should not be there.

### Steps
- `sudo ss -tulpn | grep ':80 '` : what listens on port 80, with its program and PID (Linux)
- `sudo lsof -i :80` : the same with lsof, on Linux and macOS
- `sudo fuser -v 80/tcp` : another way to ask, by port (Linux)
- `ps -fp PID` : the whole command line of that PID
- `systemctl status PID` : the service it belongs to, if it is one
- `sudo kill PID` : stop it, once you know it is safe to

### Notes
- Put your port in place of 80, and the number you found in place of PID.
- Only root can listen on ports under 1024, and `ss` and `lsof` show other users' programs only with sudo.
- A service stopped with `kill` may be started again by systemd: stop it with `sudo systemctl stop NAME`.
- macOS: `sudo lsof -nP -iTCP:80 -sTCP:LISTEN`.

### See also
- ss
- lsof
- fuser
- netstat

### Categories
network processes

Source: https://lore.guhhammer.dev/recipes/which-linux-version-is-this

## which linux version is this

The distribution, its version, the kernel and the hardware it runs on.

### Steps
- `cat /etc/os-release` : the distribution and its version
- `hostnamectl` : the same, with the kernel and the machine
- `uname -r` : the kernel's version
- `uname -m` : the processor's kind: x86_64, aarch64
- `sw_vers` : macOS's version

### See also
- uname
- hostnamectl
- lsb_release

### Categories
system

Source: https://lore.guhhammer.dev/recipes/which-package-a-file-came-from

## which package a file came from

Find the package that installed a file or a command, or the one that
would install a file you do not have yet.

### Steps
- `command -v ls` : the file a command runs, to ask about
- `dpkg -S /usr/bin/ls` : the package that installed it (Debian, Ubuntu)
- `rpm -qf /usr/bin/ls` : the same on Fedora, RHEL and openSUSE
- `pacman -Qo /usr/bin/ls` : the same on Arch
- `apt-file search bin/ncdu` : the package that would install a file not here yet (Debian, Ubuntu; needs apt-file)
- `dnf provides '*/bin/ncdu'` : the same on Fedora and RHEL

### Notes
- Every page in lore shows its command's package under VERSION, found the same way.
- macOS: Homebrew's commands are links into its folder: `ls -l "$(command -v rg)"` shows the formula.

### See also
- dpkg
- rpm
- pacman
- apt-file

### Categories
packages files

Source: https://lore.guhhammer.dev/recipes/which-shell-is-running

## which shell is running

Find out which shell runs now, which one is your default, and change it.

### Steps
- `ps -p $$` : the shell running this terminal
- `echo "$SHELL"` : your login shell, the default
- `cat /etc/shells` : the shells you can choose
- `chsh -s /bin/zsh` : make zsh your default, from the next login

### See also
- ps
- chsh

### Categories
shell

Source: https://lore.guhhammer.dev/recipes/who-is-logged-in

## who is logged in

See who is on this machine now, who was before, and the failed attempts.

### Steps
- `who` : the users logged in now, and from where
- `w` : the same, with what each one is running
- `last -n 20` : the last 20 logins
- `sudo lastb -n 20` : the last 20 failed logins
- `journalctl -u ssh --since today` : today's ssh logins and attempts (the service is `sshd` on Fedora and Arch)
- `loginctl list-sessions` : the sessions systemd knows

### Notes
- Many failed logins from one address usually mean someone is guessing passwords: see fail2ban.
- macOS: `who`, `w` and `last` work the same.

### See also
- who
- w
- last
- journalctl

### Categories
users security

Source: https://lore.guhhammer.dev/recipes/why-wont-a-service-start

## why won't a service start

Read what a systemd service said when it failed, check its unit file and
its configuration, then start it again.

### Steps
- `systemctl status NAME` : its state, its last log lines and its exit code
- `journalctl -u NAME -b -n 50 --no-pager` : its last 50 log lines since the machine started
- `systemctl cat NAME` : the unit file it runs: the command, the user, the paths
- `systemd-analyze verify NAME.service` : look for mistakes in the unit file
- `sudo ss -tulpn` : see whether another program already holds its port
- `sudo systemctl daemon-reload` : after editing a unit file, make systemd read it again
- `sudo systemctl restart NAME` : start it again, then look at its status

### Notes
- Put the service's name in place of NAME: `nginx`, `ssh`, `docker`.
- Many services check their own configuration: `sudo nginx -t`, `sudo apachectl configtest`, `sudo sshd -t`.
- "Permission denied" in the log often means a file or folder it needs belongs to another user.
- macOS uses launchd: `launchctl list | grep NAME`, and its logs with `log show --last 10m`.

### See also
- systemctl
- journalctl
- systemd-analyze

### Categories
system services

Source: https://lore.guhhammer.dev/recipes/work-with-strings-in-bash

## work with strings in bash

Join, cut, replace, change the case of and trim strings in a script, without other programs.

### Steps
- `full="$first $last"` : join strings
- `text+=' more'` : add to the end
- `echo "${text:0:5}"` : the first 5 characters
- `echo "${text//old/new}"` : replace every old with new
- `echo "${text,,} ${text^^}"` : lower case and upper case (bash 4)
- `echo "${#text}"` : its length
- `trimmed=$(echo "$text" | xargs)` : without spaces at the ends

### See also
- xargs
- printf

### Categories
shell development

