Undo the last commit, keep the changes
Removes the last commit but leaves its changes staged, ready to edit and commit again.
git reset --soft HEAD~1If the commit was already pushed, use git revert instead so you don’t rewrite shared history.
Commands
211 hand-checked commands for your Mac, PC, servers and projects. Fill in the orange blanks, hit copy, paste. No curly quotes or broken dashes. Ever.
Short tutorials with replayable terminals for the problems people hit most.
Your dev server won’t start because something is already on port 3000? Find it and stop it in under a minute.
Start guide3 minWhich undo you need depends on whether you’ve pushed. Here’s how to pick the right one without losing work.
Start guide4 minPush and pull without typing a password. Generate a key, add it to GitHub, and test it.
Start guide5 minCaches, old dependencies and Docker images quietly eat tens of gigabytes. Find them and clean them safely.
Start guide10 minFrom a fresh Mac to a ready-to-code machine: tools, Homebrew, Git identity, SSH and sensible Finder settings.
Start guide2 min“Unknown option –save”? “Invalid character”? Blogs and AI chats quietly corrupt commands. Here’s what happens and how to fix it.
Start guide3 minIsolated environments, pinned dependencies and fast installs with venv or uv.
Start guide2 minDocker can silently use 20+ GB. Measure, then clean in order from safest to most aggressive.
Start guide211 commands
Branch, commit, undo and rescue your work.
Removes the last commit but leaves its changes staged, ready to edit and commit again.
git reset --soft HEAD~1If the commit was already pushed, use git revert instead so you don’t rewrite shared history.
Creates a new commit that reverses an earlier one. Safe on shared branches because history isn’t rewritten.
git revert Replaces the message of the most recent commit.
git commit --amend -m ""Rewrites the commit. If it was already pushed you’ll need git push --force-with-lease.
Stages the file and folds it into the previous commit without changing its message.
git add && git commit --amend --no-editRewrites the last commit; avoid on commits others have pulled.
A compact view of changed files plus how far ahead or behind your branch is.
git status -sbStages new, changed and deleted files, then commits them in one go.
git add -A && git commit -m ""Creates a branch from where you are and moves onto it.
git switch -c Moves to an existing branch.
git switch Publishes the current branch with the same name and sets it as the upstream, so plain git push works next time.
git push -u origin HEADFetches remote changes and replays your local commits on top, keeping history linear.
git pull --rebaseThrows away uncommitted edits to a file and restores the last committed version.
git restore Uncommitted edits to that file are lost.
Removes a file from the staging area but keeps your edits.
git restore --staged Throws away all local commits and changes on this branch and copies the remote version.
git fetch origin && git reset --hard origin/Deletes uncommitted work and unpushed commits. Run git stash first if you might need them.
Shelves your uncommitted changes so you can switch branches with a clean tree.
git stash push -m ""Re-applies the most recent stash and removes it from the stash list.
git stash popShows every stash with its message.
git stash listA compact visual graph of all branches and commits.
git log --oneline --graph --decorate --allShows the exact changes that are staged.
git diff --stagedAnnotates every line with the commit and author that last changed it.
git blame Lists commits that added or removed the given text. Great for "when did this disappear?"
git log -S "" --onelineApplies the changes from a single commit on another branch to your current branch.
git cherry-pick Shows everywhere HEAD has been, including commits removed by reset or rebase. Use the hash with git reset or git switch -c to get them back.
git reflogLists the untracked files and folders that git clean -fd would delete. Nothing is removed.
git clean -ndRemoves every untracked file and directory from the working tree.
git clean -fdPermanently deletes untracked files (they’re not in Git, so there’s no undo). Run git clean -nd first to preview.
Deletes a branch that has been merged. Use -D to force-delete an unmerged one.
git branch -d Removes the branch from the remote repository.
git push origin --delete Renames the branch you’re on.
git branch -m Cleans up local branches that are already merged into the base branch.
git branch --merged | grep -v '^[ *]*$' | xargs git branch -dOverwrites the remote branch only if nobody else has pushed since you last fetched.
git push --force-with-leaseStill rewrites remote history; only use on branches you own.
Combines your last N commits into a single commit.
git reset --soft HEAD~ && git commit -m ""Rewrites history; avoid on commits that are already shared.
Creates an annotated version tag and publishes it.
git tag -a v -m "Release v" && git push origin vSets the author identity used on every commit on this computer.
git config --global user.name "" && git config --global user.email ""Makes git init create a main branch instead of master.
git config --global init.defaultBranch mainPoints origin at a new address, for example when switching from HTTPS to SSH.
git remote set-url origin Downloads only the most recent commit. Much faster for big repositories.
git clone --depth 1 Ranks contributors by number of commits.
git shortlog -sn --allRemoves the file from Git (for example after adding it to .gitignore) without deleting it from disk.
git rm --cached Hidden settings, Finder and Dock tweaks, system info.
Shows .pdf, .png, .app and every other extension in Finder.
defaults write NSGlobalDomain AppleShowAllExtensions -bool true && killall FinderAdds the folder path to the bottom of every Finder window.
defaults write com.apple.finder ShowPathbar -bool true && killall FinderMakes ~/Library visible in Finder permanently.
chflags nohidden ~/LibraryHides the Dock and removes the delay before it slides back in.
defaults write com.apple.dock autohide -bool true && defaults write com.apple.dock autohide-delay -float 0 && defaults write com.apple.dock autohide-time-modifier -float 0.4 && killall DockUndoes the instant auto-hide tweak.
defaults delete com.apple.dock autohide-delay && defaults delete com.apple.dock autohide-time-modifier && killall DockAdds an empty gap you can drag between apps to group them.
defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}' && killall DockRestores the original Dock apps and settings.
defaults delete com.apple.dock && killall DockYour custom Dock layout is lost.
Stops screenshots cluttering your Desktop.
mkdir -p ~/ && defaults write com.apple.screencapture location ~/ && killall SystemUIServerUse jpg, png, heic, pdf or tiff. Smaller JPGs are handy for sharing.
defaults write com.apple.screencapture type -string ""Window captures (⌘⇧4 then Space) no longer include the drop shadow.
defaults write com.apple.screencapture disable-shadow -bool truePrevents the display sleeping for the given number of seconds. Leave off -t to stay awake until you press Ctrl+C.
caffeinate -d -t Fixes websites that won’t load after a DNS change.
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponderShows the battery’s cycle count, condition and maximum capacity.
system_profiler SPPowerDataType | grep -E "Cycle Count|Condition|Maximum Capacity"Model, chip, memory and serial number.
system_profiler SPHardwareDataTypePrints the product name, version and build.
sw_versThe Mac’s address on your Wi-Fi network (use en1 if en0 is empty).
ipconfig getifaddr en0Re-copies the clipboard as plain text, dropping fonts and colours. (ClepBoard also removes hidden characters.)
pbpaste | pbcopyPuts the whole file on the clipboard without opening it.
pbcopy < Opens a Finder window for the folder your Terminal is in.
open .Speaks the text aloud. Chain it after long commands: npm run build; say done.
say ""Switches between Light and Dark appearance.
osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to not dark mode'Makes held keys repeat faster than System Settings allows. Log out and back in to apply.
defaults write NSGlobalDomain KeyRepeat -int 2 && defaults write NSGlobalDomain InitialKeyRepeat -int 15Holding a letter repeats it instead of showing accent options. Restart apps to apply.
defaults write -g ApplePressAndHoldEnabled -bool falseFinder won’t litter shared and network folders with .DS_Store files.
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool trueRemoves the download quarantine flag from an app you trust.
xattr -dr com.apple.quarantine ""Bypasses a Gatekeeper safety check. Only do this for apps from sources you trust.
Fixes Spotlight not finding files. Re-indexing takes a while in the background.
sudo mdutil -E /Restarts the audio service; it relaunches automatically.
sudo killall coreaudiodFlushes disk caches from memory.
sudo purgeTurns off the display immediately; locks if a password is required after sleep.
pmset displaysleepnowInstalls git, make, clang and other tools developers need, without the full Xcode app.
xcode-select --installRepairs, networking, winget and power tricks.
Fixes websites that won’t load after a DNS change.
ipconfig /flushdnsIP addresses, DNS servers, MAC addresses and more for every adapter.
ipconfig /allScans protected Windows files and repairs corrupted ones.
sfc /scannowFixes the component store that sfc relies on. Run it if sfc can’t repair something, then run sfc again.
DISM /Online /Cleanup-Image /RestoreHealthFinds and repairs file system errors and bad sectors on drive C.
chkdsk C: /f /rRuns at the next restart and can take hours on large drives.
Fixes many "connected but no internet" problems.
netsh winsock resetRestart afterwards. Some VPN software may need reinstalling.
The password appears next to "Key Content". Use netsh wlan show profiles to list network names.
netsh wlan show profile name="" key=clearSaves an HTML report with design vs. current capacity and usage history.
powercfg /batteryreportThe last column is the process ID (PID).
netstat -ano | findstr :Force-closes the process.
taskkill /PID /FUnsaved work in that program is lost.
Force-closes every running copy of the program.
taskkill /IM /FUpdates every app winget knows about. Run winget upgrade first to see the list.
winget upgrade --allInstalls an app by ID. Find IDs with winget search.
winget install Every installed app with its version.
winget listReboots straight into firmware settings.
shutdown /r /fw /t 0Restarts immediately. Save your work first.
Schedules a shutdown. Cancel it with shutdown /a.
shutdown /s /t Compare the hash with the one published by the download site.
Get-FileHash "" -Algorithm SHA256Makes the PATH environment variable readable.
$env:Path -split ';'Deletes files in your user temp folder. Files in use are skipped.
Remove-Item "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinueInstalls the Windows Subsystem for Linux with Ubuntu. Restart when prompted.
wsl --installPuts a text file on the clipboard.
Get-Content | Set-ClipboardShows whether a TCP connection succeeds. Handy for firewall debugging.
Test-NetConnection -Port Shows uptime in days, hours and minutes.
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTimeUseful for warranty lookups.
Get-CimInstance Win32_BIOS | Select-Object SerialNumberBrings back the full context menu without "Show more options". Delete that key to undo.
reg add "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve; Stop-Process -Name explorer -ForceEdits the registry and restarts Explorer.
Open from an administrator terminal so you can save changes.
notepad C:\Windows\System32\drivers\etc\hostsOS version, install date, memory, hotfixes and more.
systeminfoPackages, services, processes and permissions.
Refreshes package lists and installs all available updates.
sudo apt update && sudo apt upgrade -yRefreshes metadata and upgrades all packages.
sudo dnf upgrade --refreshSyncs the package database and upgrades the system.
sudo pacman -SyuDeletes packages nothing depends on and clears the download cache.
sudo apt autoremove -y && sudo apt cleanDisk usage of every mounted drive in human-readable sizes.
df -hSize of each item in the current folder, smallest to largest.
du -sh * | sort -hUsed, free and available RAM and swap.
free -hThe ten processes using the most memory.
ps aux --sort=-%mem | head -n 10Asks the process to exit. If it ignores you, use kill -9 to force it.
kill Stops every process whose command line matches.
pkill -f Matches broadly; check with pgrep -fl first.
Shows whether a service is running and its latest log lines.
systemctl status Stops and starts the service.
sudo systemctl restart Enables the service at boot and starts it immediately.
sudo systemctl enable --now Streams new log lines as they arrive. Ctrl+C to stop.
journalctl -u -fName, version and ID of the Linux distribution.
cat /etc/os-releaseKernel name, version and architecture.
uname -aLets you run it with ./script.sh.
chmod +x Fixes "permission denied" on files created by root.
sudo chown -R $USER:$USER Adds the user to the sudo group (wheel on Fedora/Arch). They need to log in again.
sudo usermod -aG sudo Every open TCP/UDP port with the process that owns it.
sudo ss -tulpnAllows incoming traffic on a port (Ubuntu’s ufw). Enable the firewall with sudo ufw enable.
sudo ufw allow /tcpAlways allow SSH (22) before enabling ufw on a remote server, or you’ll lock yourself out.
Opens your cron table. Each line is: minute hour day month weekday command.
crontab -eRefreshes the output on screen. Ctrl+C to stop.
watch -n For Wayland desktops. On X11 use: xclip -selection clipboard < file.
wl-copy < Model, cores, threads and cache sizes.
lscpuPorts in use, DNS, IPs, HTTP and certificates.
Shows the program and PID listening on or connected to the port.
lsof -i :Force-stops every process using the port. Fixes "address already in use".
kill -9 $(lsof -ti :)Force-kills without letting the program save. Check with lsof -i first.
Finds the process listening on the port and stops it.
Stop-Process -Id (Get-NetTCPConnection -LocalPort ).OwningProcess -ForceEvery program accepting connections, with numeric addresses and ports.
sudo lsof -iTCP -sTCP:LISTEN -n -PThe IP the internet sees you as.
curl -s https://ifconfig.mePrints the addresses a domain resolves to. Add a record type like MX or TXT after the domain.
dig +short Shows the DNS server used and the addresses for a domain.
nslookup Sends four pings and reports latency and packet loss. (On Windows, just ping host.)
ping -c 4 Lists every hop between you and the destination. On Windows use tracert.
traceroute Fetches only the response headers: status code, caching, redirects, server.
curl -I Saves the file with its original name, following redirects.
curl -LO Prints the total time for one request.
curl -o /dev/null -s -w "%{time_total}s\n" Shows the certificate’s valid-from and valid-until dates.
echo | openssl s_client -connect :443 -servername 2>/dev/null | openssl x509 -noout -datesServes the current folder at http://localhost:8000. Great for testing static sites.
python3 -m http.server Registrar, creation and expiry dates and name servers.
whois Find, search, archive, sync and checksum.
Searches the folder and all subfolders for matching names.
find -name ""Lists files bigger than the size you choose, with their sizes.
find -type f -size + -exec ls -lh {} \; 2>/dev/nullEvery line containing the text, with file names and line numbers.
grep -rn "" Much faster than grep and skips .gitignore’d files. Install with brew install ripgrep.
rg ""Creates a compressed archive.
tar -czvf Unpacks the archive into the current folder.
tar -xzvf Creates a .zip that opens anywhere.
zip -r Extracts the zip into the given folder.
unzip -d Copies only what changed and preserves timestamps and permissions. The trailing slash on the source means "its contents".
rsync -avh --progress Prints new lines as they’re written. Ctrl+C to stop.
tail -f Number of lines (add -w for words).
wc -l Verify downloads against the published hash. On Linux you can also use sha256sum.
shasum -a 256 Makes a link that points to the original file or folder.
ln -s Visual folder structure, limited to N levels. Install with brew install tree.
tree -L Renames every .txt in the folder to .md.
for f in *.; do mv -- "$f" "${f%.}."; doneRenames files in place. Try it on a copy first.
Removes macOS folder metadata files from the current folder down.
find . -name ".DS_Store" -type f -deleteFrees up gigabytes from old projects. Reinstall later with npm install.
find . -name "node_modules" -type d -prune -exec rm -rf {} +Deletes folders permanently. Run it from your projects folder, not from / or ~.
Containers, images, Compose and cleanup.
Running and stopped containers with their status and ports.
docker ps -aStarts a container in the background and maps a port to your machine.
docker run -d -p : --name Opens a shell in a fresh container that is deleted when you exit.
docker run -it --rm bashUse bash instead of sh if the image has it.
docker exec -it shLast 100 lines, then streams new ones.
docker logs -f --tail 100 Builds from the Dockerfile in the current folder.
docker build -t .Works the other way round too.
docker cp : Builds images if needed and starts all services in the background.
docker compose up -d --buildLeave out the service name to see all of them.
docker compose logs -f Stops and removes the containers and network. Add -v to also delete volumes (data).
docker compose downGracefully stops every running container.
docker stop $(docker ps -q)Space used by images, containers, volumes and build cache.
docker system dfDeletes untagged leftover layers from old builds. Asks before deleting.
docker image pruneDeletes all stopped containers. Asks before deleting.
docker container pruneRemoves stopped containers, unused networks, every image not used by a container, and the build cache.
docker system prune -aYou’ll need to re-download or rebuild images. Volumes are kept unless you add --volumes.
Install, update, debug and scaffold projects.
Check which versions you’re running.
node -v && npm -vThe classic fix for weird dependency errors.
rm -rf node_modules package-lock.json && npm installRegenerates the lockfile, so versions may change within your semver ranges.
Deletes node_modules and installs exactly what package-lock.json says. Best for CI and reproducible builds.
npm ciCurrent, wanted and latest versions of every dependency.
npm outdatedBumps every version in package.json to the newest release.
npx npm-check-updates -u && npm installIncludes major versions that may have breaking changes. Commit first.
Shows which dependencies pulled it in.
npm explain Everything installed with npm install -g.
npm ls -g --depth=0Fixes some corrupted-download errors.
npm cache clean --forceUpgrades packages with known vulnerabilities where it’s safe to do so.
npm audit fixRequires nvm (or nvm-windows).
nvm install --lts && nvm use --ltsScaffolds a new Next.js project with prompts for TypeScript, ESLint and more.
npx create-next-app@latest Choose React, Vue, Svelte and more.
npm create vite@latest Turns on pnpm using Node’s built-in Corepack.
corepack enable pnpmRun npm run with no name to list available scripts.
npm run Virtual environments, packages and uv.
Keeps this project’s packages separate from the system.
python3 -m venv .venv && source .venv/bin/activateIf activation is blocked, run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
python -m venv .venv; .venv\Scripts\Activate.ps1Installs every package listed.
pip install -r requirements.txtWrites exact versions of everything in the environment.
pip freeze > requirements.txtUse python instead of python3 on Windows.
python3 -m pip install --upgrade pipuv is a very fast Python package and project manager.
curl -LsSf https://astral.sh/uv/install.sh | shPipes a script from the internet into your shell. This is the official installer; read it first if unsure.
Creates pyproject.toml, a starter main.py and a .gitignore.
uv init && cd Installs it into the project environment and records it in pyproject.toml.
uv add Runs inside the project environment, syncing dependencies first.
uv run Formats a JSON file with indentation. Also works on piped input.
python3 -m json.tool Path and version of the active interpreter.
which python3 && python3 --versionKeys, servers, tunnels and file transfer.
Creates a modern, secure key pair in ~/.ssh. Press Enter to accept the default location.
ssh-keygen -t ed25519 -C ""Puts the public key on the clipboard to paste into GitHub, GitLab or a server.
pbcopy < ~/.ssh/id_ed25519.pubPuts the public key on the clipboard.
Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub | Set-ClipboardStores the passphrase in Keychain so you’re not asked every time.
ssh-add --apple-use-keychain ~/.ssh/id_ed25519Confirms GitHub accepts your key.
ssh -T git@github.comLets you log in without a password from now on.
ssh-copy-id @Copies a file over SSH. Add -r for folders.
scp @:Open http://localhost:8080 to reach the server’s port 80 through an encrypted tunnel.
ssh -L :localhost: @SSH refuses private keys other users can read.
chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_ed25519Install, update and clean up Mac apps.
The official one-line installer from brew.sh.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"Runs a script from the internet with your permissions. This is Homebrew’s official installer.
Refreshes Homebrew and upgrades all installed formulae and casks.
brew update && brew upgradeRemoves old versions and the entire download cache.
brew cleanup --prune=allInstalls a GUI app. Search names with brew search.
brew install --cask All installed formulae and casks.
brew listChecks your setup and explains how to fix issues.
brew doctorStarts a database or server and keeps it running at login.
brew services start Saves everything installed to a Brewfile. Restore on a new Mac with brew bundle --file=~/Brewfile.
brew bundle dump --file=~/BrewfileEvery command copies as plain, clean text: no curly quotes, no long dashes, no invisible characters.