Bash One-Liners to Try in a Real Linux Terminal
Someone sent you a command
It gets typed into a real Linux machine running in this tab. Nothing runs until you press Enter, so you can look it over first.
A good one-liner does in one line what would otherwise take a script, a spreadsheet or a quiet afternoon. These are the bash one-liners worth knowing by heart, each with a note on how it works, and each with a ▶︎ Try it button that types it into the real Linux machine below, against real files, stopping short of the final Enter.
Runs in
↓ Now in the terminal: press Enter when you're ready.
Downloads about 20 MB, then runs entirely in this tab.
Best with a physical keyboard.
The terminal's moved, to stay in sight while you work down the page.
Why it's safe to run
Nothing runs until you press Enter, and then only on an emulated PC inside this tab, which can't touch your files. If it breaks anything in there, Reset puts it back.
Got one of your own? Share under the terminal makes a link to it. How these links work
Every guide on the site has commands with a ▶︎ Try it button that types them into this machine. Pick a tool and have a go.
Every ▶︎ Try it button on this page types its command into a real Linux machine running in this tab, with the tools already installed. Break it as much as you like.
Counting things
Section titled “Counting things”Logs, spreadsheets and API responses are all text, and most questions about them come down to how many, how much, or which ones. Each of these answers one in a line.
Count anything with sort and uniq
Section titled “Count anything with sort and uniq”sort | uniq -c | sort -rn is the most useful pipeline in Unix. Cut out the field you care about, sort it so the duplicates sit
together, count each run of them, then sort the counts, biggest first. Here it is on a web
server’s access log, tallying the status codes:
cut -d' ' -f9 access.log | sort | uniq -c | sort -rn 7 200 3 404 1 500 1 304The first sort isn’t optional: uniq only collapses duplicates that are next to each other, so
without it you get a count of each streak rather than each value. Swap -f9 for -f1 to count
IP addresses, or -f7 for the paths asked for, which is how you find out who’s been rattling
/wp-login.php on a site that has never run WordPress.
Total a column in a CSV
Section titled “Total a column in a CSV”awk splits each line on commas, adds quantity times price to a running total per customer, and
prints the totals at the end. NR > 1 skips the header line:
awk -F, 'NR > 1 { t[$3] += $5 * $6 } END { for (c in t) printf "%8.2f %s\n", t[c], c }' orders.csv | sort -rn 509.50 Bloggs & Co 445.90 Acme Ltd 178.00 Initechawk hands back the totals in whatever order it likes, hence the sort -rn. This works for as
long as nobody puts a comma inside a quoted field, at which point it quietly adds up the wrong
columns. The awk cheat sheet
covers that, and the rest of what awk can count.
Pick fields out of JSON
Section titled “Pick fields out of JSON”The servers running hotter than 80% CPU, by name. .servers[] walks the array, select() keeps
the matches, and -r prints plain text rather than JSON strings in quotes:
jq -r '.servers[] | select(.cpu > 0.8) | .name' servers.jsonweb-01db-01Anything you’d do with grep on JSON, jq does properly. The jq
guide has the rest, including the gotchas.
Add up a list of numbers
Section titled “Add up a list of numbers”paste -sd+ joins the lines with plus signs, and bc does the sum. Here, every number from 1 to
100, which took Gauss about as long as it takes to type this:
seq 1 100 | paste -sd+ | bc5050Anything that prints a number per line can go in front of it: file sizes, durations, the second
column of something via cut.
Finding, renaming and changing files in bulk: the jobs a file manager makes you do one at a time.
See what’s eating the disk
Section titled “See what’s eating the disk”The size of everything in the home directory, one level deep, biggest first:
du -hd1 ~ | sort -rh | head -546.7M /home/ninja27.0M /home/ninja/.cache19.1M /home/ninja/.local412.0K /home/ninja/demo32.0K /home/ninja/strict-modeThe first line is the total. On this machine the rest is mostly tldr’s cache of other people’s
documentation and Neovim’s plugins, which is roughly true of most developers’ home directories
as well. sort -h understands K, M and G, so 46.7M sorts above 412K rather than below it.
Point it at / with sudo when a server runs out of space, and add -x to stay on one disk.
Find and replace across a whole project
Section titled “Find and replace across a whole project”ripgrep lists the files that mention a name, and sed renames
it in each of them:
rg -l0 TIMEOUT | xargs -0 sed -i 's/TIMEOUT/TIMEOUT_SECS/g'Run rg -l TIMEOUT on its own first, to see what you’re about to change:
src/config.pysrc/main.pytests/test_config.py-l0 and -0 separate the file names with a null byte rather than a newline, so a name with a
space in it arrives in one piece. The classic version is grep -rl, which works too, but it also
searches .git and anything .gitignore excludes, so sed goes on to edit files you didn’t mean
it to. rg skips both. On macOS, sed -i wants an argument, so it’s sed -i '' there, or use
sd, which reads the same everywhere:
rg -l0 TIMEOUT | xargs -0 sd TIMEOUT TIMEOUT_SECS. Either way, do it on a clean working tree, so
git diff afterwards shows exactly what changed. The ripgrep
guide has more on searching and replacing.
Rename a batch of files, dry run first
Section titled “Rename a batch of files, dry run first”Change every .py in a directory to .txt. ${f%.py} is the file name with .py chopped off
the end, and the echo in front of mv means this only prints what it would do:
for f in *.py; do echo mv -- "$f" "${f%.py}.txt"; donemv -- config.py config.txtmv -- main.py main.txtmv -- server.py server.txtIf that’s what you wanted, press the up arrow, delete the echo and run it again. The -- stops
a file named -rf being read as options, which sounds paranoid until the day it isn’t.
Back up a file before you edit it
Section titled “Back up a file before you edit it”cp ~/.bashrc{,.bak}Brace expansion turns ~/.bashrc{,.bak} into two words, the name with nothing added and the name
with .bak added, so cp gets both. Put echo in front to watch the shell do it:
$ echo cp ~/.bashrc{,.bak}cp /home/ninja/.bashrc /home/ninja/.bashrc.bakThe same trick renames in place: mv notes.{txt,md}.
Make a directory and go into it
Section titled “Make a directory and go into it”mkdir -p ~/scratch/today && cd "$_"$_ is the last argument of the previous command, so cd goes to the directory mkdir just
made, however long its name was. -p makes the parents as well, and doesn’t complain if the
directory is already there.
Count lines of code
Section titled “Count lines of code”find ~/demo -name '*.py' -exec wc -l {} + 7 /home/ninja/demo/src/server.py 11 /home/ninja/demo/src/main.py 11 /home/ninja/demo/src/config.py 5 /home/ninja/demo/tests/test_config.py 34 totalThe + hands wc every file at once, which is what gets you the total at the end; \; would
run it once per file, and leave the adding up to you. fd
says the same thing in fewer characters, and skips what .gitignore excludes:
fd -e py . ~/demo -X wc -l.
The shell itself
Section titled “The shell itself”The shell does more than start programs: it remembers what you ran, times things, and makes things up. All of these work in zsh too.
Rerun the last command with sudo
Section titled “Rerun the last command with sudo”cat /etc/shadowsudo !!!! is the whole of the previous command, so the second line is the first one again with sudo
in front. The shell prints what it expanded to before running it:
$ cat /etc/shadowcat: can't open '/etc/shadow': Permission denied$ sudo !!sudo cat /etc/shadowroot:!*:20760:0:::::bin:!::0:::::The Try it button runs the first line and leaves the second for you. It works in bash and zsh,
and !$ is the same idea for just the last word: mkdir new-thing then cd !$.
Fix a typo in the last command
Section titled “Fix a typo in the last command”echo hello wrold^wrold^world^old^new reruns the previous command with the first old swapped for new. Faster than going
back for it with the arrow keys, and the readline
shortcuts cover the cases where it isn’t.
A stopwatch
Section titled “A stopwatch”time readPress Enter to start, and Enter again to stop. read waits for a line of input, and time says
how long it waited:
real 0m4.212suser 0m0.000ssys 0m0.000sIdeal for timing a kettle, a build, or how long a meeting took to reach its first decision.
Generate a random password
Section titled “Generate a random password”Twenty letters and digits from the kernel’s random number generator. tr -dc deletes everything
that isn’t in the list, so only those characters survive:
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 20; echovqHmpiZYaK8DUv6qQ9pRLC_ALL=C is for macOS, whose tr otherwise gives up with “Illegal byte sequence” at the first
random byte that isn’t valid text. The final echo adds the newline head -c leaves off, so the
prompt doesn’t end up glued to the password.
Two for the repository: one to find the code that keeps changing, and one to take back a commit you made too soon.
Find the files that change most
Section titled “Find the files that change most”git log --format= --name-only | sort | uniq -c | sort -rn | head 3 src/config.py 1 tests/test_config.py 1 src/widgets/button.js 1 src/server.py 1 src/main.py--format= prints no commit details at all, just the files each commit touched, and the tally
pipeline from the top of the page counts them. In a real repository, the top of this list is
where the bugs live, or at least where they keep getting fixed.
Undo the last commit, but keep the changes
Section titled “Undo the last commit, but keep the changes”git reset --soft HEAD~1 && git status --shortA .env.exampleMM src/config.pyThe commit goes, and everything in it goes back to being staged, ready to be committed again
properly: the A and the first M are the undone commit’s changes, and the second M is
whatever you hadn’t staged before. Don’t do this to a commit you’ve already pushed. The git
settings guide has the config that makes the rest of git less
eager to surprise you.
And one for no reason
Section titled “And one for no reason”Not every one-liner has to earn its keep.
A clock
Section titled “A clock”while sleep 1; do clear; date +%T | figlet | lolcat; done ____ _ ____ _____ _________|___ \/ |_| ___|___ ||___ /___ \ __) | (_)___ \ / (_) |_ \ __) | / __/| |_ ___) |/ / _ ___) / __/|_____|_(_)____//_/ (_)____/_____|A loop with sleep as its condition runs forever, once a second, until Ctrl+C. figlet draws the
time in large letters, and lolcat paints them in a rainbow, which the block above can’t show you
and the terminal can. Fun terminal commands has the rest of the
toys, and tty-clock for anyone who wants a clock that someone actually designed.
Where next
Section titled “Where next”Most of these are two or three tools in a pipe, and each of those has a page of its own here. The awk cheat sheet and the jq guide go further into totting up text and JSON, and the ripgrep cheat sheet does the same for finding things. Once a one-liner outgrows its line and becomes a script, start it with bash strict mode. And the machine above has more to try on its own page, along with a list of what’s installed.
This page is also where shared command links open, so if you followed one and found no command at the top, it lost the end of itself on the way.
Find terminal ninja useful? Support it on Ko-fi