Skip to content

Bash One-Liners to Try in a Real Linux Terminal

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.

Downloads about 20 MB, then runs entirely in this tab.
Best with a physical keyboard.

Not running

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.

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:

Terminal window
cut -d' ' -f9 access.log | sort | uniq -c | sort -rn
7 200
3 404
1 500
1 304

The 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.

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:

Terminal window
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 Initech

awk 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.

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:

Terminal window
jq -r '.servers[] | select(.cpu > 0.8) | .name' servers.json
web-01
db-01

Anything you’d do with grep on JSON, jq does properly. The jq guide has the rest, including the gotchas.

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:

Terminal window
seq 1 100 | paste -sd+ | bc
5050

Anything 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.

The size of everything in the home directory, one level deep, biggest first:

Terminal window
du -hd1 ~ | sort -rh | head -5
46.7M /home/ninja
27.0M /home/ninja/.cache
19.1M /home/ninja/.local
412.0K /home/ninja/demo
32.0K /home/ninja/strict-mode

The 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.

ripgrep lists the files that mention a name, and sed renames it in each of them:

Terminal window
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.py
src/main.py
tests/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.

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:

Terminal window
for f in *.py; do echo mv -- "$f" "${f%.py}.txt"; done
mv -- config.py config.txt
mv -- main.py main.txt
mv -- server.py server.txt

If 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.

Terminal window
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.bak

The same trick renames in place: mv notes.{txt,md}.

Terminal window
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.

Terminal window
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 total

The + 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 does more than start programs: it remembers what you ran, times things, and makes things up. All of these work in zsh too.

Terminal window
cat /etc/shadow
sudo !!

!! 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/shadow
cat: can't open '/etc/shadow': Permission denied
$ sudo !!
sudo cat /etc/shadow
root:!*: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 !$.

Terminal window
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.

Terminal window
time read

Press Enter to start, and Enter again to stop. read waits for a line of input, and time says how long it waited:

real 0m4.212s
user 0m0.000s
sys 0m0.000s

Ideal for timing a kettle, a build, or how long a meeting took to reach its first decision.

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:

Terminal window
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 20; echo
vqHmpiZYaK8DUv6qQ9pR

LC_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.

Terminal window
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”
Terminal window
git reset --soft HEAD~1 && git status --short
A .env.example
MM src/config.py

The 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.

Not every one-liner has to earn its keep.

Terminal window
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.

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