9 essential command pipelines that simplify everyday Linux


The pipeline feature is one of the driving forces behind the Linux philosophy, a single character that changes everything about how you work. By connecting the output of one command to the input of another, you can chain small programs together, creating a tool that is far greater than the sum of its parts.

If you’re struggling to see the value in pipes, or just looking to understand their practical use a bit better, there’s no better place to begin than these common, effective examples.

grep | less

Filter data and page the results

A typical grep command can return many results, especially if you’re using trial and error to refine a regular expression. A command like grep '[Qq]' /usr/share/dict/words will produce more than one screen of output:

A screen showing a list of words, one on each line, beginning with the letter "v" and ending with the letter "z."

To see more than just the last page of results, you’ll need to use a pager. The grep command doesn’t directly support one, but you can pipe any set of output to a pager and view it page-by-page:

grep '[Qq]' /usr/share/dict/words | less
A screen of words, one on each line, all beginning with the letter "a", with a status line at the very bottom reading "lines 1-14."

tail | grep

The tail command is useful any time you want to explore the last lines of a file, most often a log file. Its -f option provides a live view of a file (or standard input), continuing to print lines that are appended to the file. It’s perfect for monitoring log files, like the apache access log:

The tail command, run with the -f option, showing lines from an apache access log.

You’ll probably want to filter such log lines, however, looking for specific data that matches URLs, specific messages, response codes, and so on. The grep tool is great for this, and it pairs perfectly with tail in a pipeline like tail -f file | grep pattern.

You may forget about the order of these commands and expect them to work in reverse. However, piping grep to tail -f will cause the pipeline to end immediately because tail ignores -f when the input is a pipe.

history | grep

Quick access to commands you’ve run before

The history command is incredibly useful, giving you access to commands you’ve previously run. But your history contains a lot of detail; by default, in bash, it’s the last 500 commands. And it can be even more, especially if you’ve set up unlimited history.

A list of commands, each printed alongside a unique id number.

This is another perfect opportunity for grep to filter out only the lines that you’re really interested in:

history | grep ls

sort | uniq

Simple summary info from structured data

The sort and uniq filters are so useful when combined with other commands that you’ll see them used in pipelines time and time again. uniq is short for “unique,” and both commands do pretty much exactly what you’d expect, based on their names.

Here’s an example of a pipeline that shows which IP addresses have visited a website, and how many times each has sent a request:

</var/log/apache2/access_log cut -f1 -d' ' | sort | uniq -c

This pipeline involves three commands, the first of which—cut—extracts the IP address field from a standard Apache access log. sort will order all the lines of input that are piped to it, while uniq removes duplicates and, with the -c option, counts the total number. You’ll end up with a nice summary:

A command piping sort to uniq that shows a short list of IP addresses, each with a count alongside it.

df | tee

Get disk space reports on screen and in a file

The tee command was made for the pipeline; its core operation is to copy its standard input to standard output. That might seem useless, except for the one extra feature it provides: saving that same input to one or more files.

Normally, to save the output of a command, you can use redirection:

echo "Hello world" > myfile.txt

However, redirecting that output prevents you from viewing it on screen or piping it somewhere else:

A command redirecting its output to a file, with no output shown on screen.

Using the tee command, you can save output to a file, but still have it in the pipeline, for further processing or output on screen:

echo "Hello world" | tee myfile.txt
A command piped to tee, showing its output on screen.

You can even supply multiple arguments to tee, in case you want to save output to more than one file at once.

tee is a great choice if you ever want to check the output of a command, but keep a record of it at the same time. For example, you can use the df command to report on disk usage:

df -h | tee diskusage.txt

Piping the output to tee means that it’ll still show up on screen, but you’ll get a permanent record stored in a file too.

echo | xargs

Copy a file to multiple directories

The xargs command is a bit like tee; it’s a “meta command” that alters how the command line itself operates. xargs lets you inject its input into arguments of another command, so it often comes in use as part of more complicated pipelines.

By default, xargs converts each space-delimited value into an argument, appending them to a command that you pass it. You can also use the -n option to call the command more than once, passing in a slice of arguments each time, as in this example:

echo "dir1 dir2" | xargs -n 1 cp -v myfile.md

The cp command will not copy a file to multiple directories, so this pipeline instructs xargs to provide one argument at a time, expanding to:

cp -v myfile.md dir1
cp -v myfile.md dir2

curl | jq

Process data retrieved from a web API

If you’ve ever used curl to access a web API from the command-line, you’ve probably been faced with a long response containing JSON that you need to process further:

A curl command showing JSON-formatted output.

The curl command is great at handling all sorts of web requests, but further processing requires other commands like, in this case, jq, the command-line JSON processor. Using jq, you can write filters to transform JSON data into more readable or appropriate forms. For example, the simplest thing you can do is use the identity operator (.) to copy the input, but validate and format it too:

curl -s https://catfact.ninja/fact | jq '.'
A curl command piped to jq showing the JSON result formatted with newlines and indents, and syntax highlighting.

You can write all sorts of filters to slice and dice the data however you want. The example above returns a single object with fact and length properties, which you can extract with a simple filter:

curl -s https://catfact.ninja/fact | jq -r '.fact'

du -sh * | sort -h

Find your biggest files and directories

The du program reports the total size of files and directories that you pass it:

The du command showing a set of directories with sizes (in blocks) alongside each one.

This is great, but you’re probably looking for the files that are taking up the most disk space. Unfortunately, du offers no built-in way to sort its output. Fortunately, there’s the good old sort command.

sort is a filter command that orders its input and prints it as output. You can use it to sort the standard output of du:

du -s * | sort

This is OK, but the output is in blocks, which isn’t the most readable. To do the same thing, with more readable sizes, use the -h option for both commands:

du -sh * | sort -h

Even though the output doesn’t sort naturally, sort is clever enough to recognize the format and sort kilobytes before megabytes, etc.

The du command piped to sorted, showing human-readable sizes (like "184K" and "41M") ordered correctly.

date | md5sum

The quickest way to generate a decent password

I reach for this one all the time when generating passwords; it’s quick, effective, and easy to remember. The md5sum will hash its input using the MD5 algorithm, and print the result:

The date command piped to the md5sum command showing a random-looking string of 32 hexadecimal characters.

When I need a random set of hexadecimal characters, this is my go-to. You could use it for a variety of purposes, including generating random CSS colors, but it’s pretty convenient for password generation too.

This may not be the most secure way to pick a password. Please consult security advice before choosing a password, especially for high-risk uses!


With practice, common pipelines will become second nature

If there’s a pipeline you haven’t used before, it can take some time to become familiar with it. Practice any that seem useful and, after a short time, you’ll start piping to grep or sort so often that you’ll wonder how you ever survived without them.



Source link

Leave a Reply

Subscribe to Our Newsletter

Get our latest articles delivered straight to your inbox. No spam, we promise.

Recent Reviews


The first computer my family owned was an 80286 IBM clone, and it had lots of ports, none of which looked the same. There was a big 5-pin DIN for the keyboard, a serial port, a parallel port, a game port for our joystick, and of course, the VGA port for the monitor.

In comparison, a modern computer has much less diversity in the port department. Not only are there fewer types of ports, but the total number may be quite low as well. When we move to modern laptops, it can be much more minimalist. Some laptops have just a single port on the entire machine! Is this a bad thing? As with anything, the extremes are rarely ideal, but I’d say overall, this has been a pretty positive development for PCs.

The port explosion era was never sustainable

It was more like a port infection

You see, the reason we had so many ports for so long is that people kept inventing new interfaces to make up for the shortcomings of existing ones. However, instead of the newer, better interfaces making the old ones obsolete, they just became additive as perfectly summarized in this classic XKCD comic.

A comic illustrates how competing standards multiply: first showing 14 competing standards, then people agreeing to create one universal standard, followed by a final panel showing there are now 15 competing standards. Credit: Randall Munroe (CC-BY-NC)

In laptops, the need for so many ports reached ridiculous heights. In this video posted by X user PC Philanthropy, you can see his Sager/Clevo D9T absolutely packed with all the trimmings leading to a rather massive laptop.

It is undeniably a cool machine, but obviously goes against the principle of portable computing. Also, every port you install means power and space that could have been taken up by something else. That’s true for laptops and desktops.



















Quiz
8 Questions · Test Your Knowledge

PC ports and motherboard I/O
Trivia challenge

Think you know your USB from your PCIe? Put your connector knowledge to the test.

PortsStandardsHardwareConnectorsMotherboards

Which USB connector type is fully reversible, meaning it can be plugged in either way?

Correct! USB Type-C features a symmetrical oval design that lets you insert it in either orientation. Introduced in 2014, it has become the dominant connector for modern devices and supports everything from data transfer to video output and fast charging.

Not quite — the answer is USB Type-C. The older USB Type-A connector (the flat rectangular one) famously required you to flip it at least twice before getting it right. USB Type-C’s reversible design was one of its biggest selling points when it launched in 2014.

What does the ‘x16’ in a PCIe x16 slot refer to?

Exactly right! PCIe x16 means the slot has 16 data lanes, allowing significantly more bandwidth than smaller x1 or x4 slots. This is why discrete graphics cards almost always use x16 slots — they need that extra throughput to feed pixel data to your display.

Not quite — the ‘x16’ refers to the number of data lanes. More lanes mean more simultaneous data paths between the CPU and the card. Graphics cards use x16 slots because their massive data demands require all 16 of those lanes working together.

Which port on a motherboard is most commonly used to connect a display directly to the CPU’s integrated graphics?

That’s correct! The HDMI and DisplayPort connectors found on a motherboard’s rear I/O panel are wired directly to the CPU’s integrated graphics unit. If you have a discrete GPU installed, you should use that card’s outputs instead for best performance.

The right answer is the HDMI or DisplayPort connectors on the rear I/O panel. These ports bypass the discrete GPU entirely and tap into the CPU’s built-in graphics. It’s a common troubleshooting trap — plugging a monitor into the motherboard instead of the GPU and wondering why nothing works.

What is the primary function of the 24-pin ATX connector on a motherboard?

Spot on! The 24-pin ATX connector is the main power connector that delivers multiple voltage rails — including 3.3V, 5V, and 12V — from the power supply to the motherboard. Without it seated properly, your PC simply won’t power on at all.

The correct answer is delivering power from the PSU to the motherboard. The 24-pin ATX connector is the big wide plug you’ll find on every modern motherboard. It supplies several different voltage levels that the board distributes to components. PCIe cards get their supplemental power from separate 6- or 8-pin connectors directly from the PSU.

Which of the following rear I/O ports transmits both audio and video in a single cable and is most commonly found on modern motherboards?

Correct! HDMI carries both high-definition audio and video over a single cable, making it one of the most convenient display connectors available. It became standard on motherboards as integrated graphics improved, and modern versions support 4K and even 8K resolutions.

The answer is HDMI. VGA is analog-only and carries no audio, DVI-D is digital video only without audio, and S-Video is an older analog format. HDMI bundles both audio and video digitally, which is why it became the go-to connector for TVs, monitors, and motherboard rear panels alike.

What maximum theoretical data transfer speed does USB 3.2 Gen 2×2 support?

Impressive! USB 3.2 Gen 2×2 achieves 20 Gbps by using two 10 Gbps lanes simultaneously — that’s what the ‘2×2’ means. It requires a USB Type-C connector and is most commonly found on high-end motherboards, making it ideal for fast external SSDs.

The correct answer is 20 Gbps. The ‘2×2’ in the name is the key clue — it bonds two 10 Gbps channels together. USB naming got notoriously confusing around this era, with the same physical port potentially supporting very different speeds depending on the generation label printed in the spec sheet.

What is the role of the M.2 slot found on most modern motherboards?

Well done! M.2 is a compact form-factor slot that most commonly hosts NVMe SSDs, which connect via PCIe lanes for blazing-fast storage speeds. Some M.2 slots also support SATA-based SSDs and Wi-Fi/Bluetooth combo cards, making the slot surprisingly versatile.

The correct answer is housing compact storage drives or wireless cards. M.2 replaced the older mSATA standard and supports both PCIe NVMe drives and SATA drives depending on the slot’s keying. NVMe M.2 drives can achieve sequential read speeds many times faster than traditional SATA SSDs.

Which audio connector color on a standard PC rear I/O panel is designated for the main stereo line output to speakers or headphones?

That’s right! The green 3.5mm jack is the standard line-out port used for speakers and headphones in the PC audio color-coding scheme. Blue is line-in for recording, and pink is the microphone input — a color system that’s been consistent across PC motherboards for decades.

The correct answer is green. PC audio jacks follow a long-standing color convention: green for headphones and speakers, blue for line-in (recording from external sources), and pink for the microphone. It’s one of those legacy standards that has quietly persisted even as USB and digital audio have become more common.

Challenge Complete

Your Score

/ 8

Thanks for playing!

USB-C (almost) solved the problem

So close, but not quite there yet

Released to the public in the mid ’90s, USB came to the rescue. The “U” is for “Universal” and for the most part USB has lived up to that promise. Now there was one port that handled data and power. More importantly, USB is fully backwards compatible. So if you plug a USB 1.1 device into a modern USB port, it should work. Whether you can get software drivers for it is another story, but it will talk to the host device.

USB-C has proven to be less universal than I’d like, and the situation is still far better than it used to be. A single USB-C port on one of my laptops can act as a video output for just about anything, even an old VGA monitor.

A Macbook, CRT monitor, and iPad connected together. Credit: Sydney Louw Butler/How-To Geek

My smaller laptops don’t need special chargers anymore, and the latest laptops can pull 240W over USB-C, which is enough for all but the beefiest desktop replacement machines. There is no type of peripheral I can think of that doesn’t give you the option to use it over USB.

But the complaints aren’t so much that we only get USB these days, it’s more that we get so little of it.

Minimal I/O enables better hardware design

Harder, better, faster, stronger

When you only put a handful of USB-C ports on a mobile computer, you reap numerous benefits. The low profile of USB-C means the laptop can be thinner, and the frame can be a stronger and more rigid unibody design. Internally, you have room for more battery, larger performance components, or better cooling.

A green Apple MacBook Neo on display on a wooden table with a product sign behind it. Credit: Patrick Campanale / How-To Geek

It also means the internals can be simpler, and cheaper to design and fabricate, though whether those savings are passed on to customers is another story altogether.

Wireless and cloud-first workflows reduce physical dependency

I guess they are “air” ports

Perhaps the first sign of major change was when smartphones dropped headphone jacks, but the fact is that wireless technologies are now good enough for most peripheral and data connections. So, there’s no need to connect them directly to a port on a computer. Which, in turn, means that there’s no reason to have as many ports on the computer in the first place.

I can’t remember the last time I used a wired mouse or keyboard, and I only use Ethernet for devices that need extremely high speeds, low latency, or improved reliability. For normal day-to-day use, modern Wi-Fi is just fine. So while your laptop might not have as many wired ports on the outside, those wireless chips on the inside still give it numerous connectivity options for audio, input, and data transfer.

You could even make the same argument about storage to some extent, with many thin and light systems leaning on cloud storage to make up for a lack of ports to connect external storage.

MacBook Neo colors on a white background.

Operating System

macOS

CPU

A18 Pro

The MacBook Neo with the A18 Pro chip is Apple’s most affordable laptop yet, with all-day battery life and buttery-smooth performance in a thin and light profile.



The dongle backlash misses the bigger picture

The last bit of the port protest centers around dongles, but I never understood the complaints. Having one port that can be broken out into whatever ports you need using a little box is amazing. It makes ports optional and gives you the choice. If you never plug your laptop into anything, why deal with all the ports you’ll never use?

Likewise, if you only ever use ports with your laptop when you dock it at a desk, then you can just leave your dongle ready to go on your desk, but throwing a small dongle in your laptop sleeve or bag in case you might need it is a small price to pay for all the benefits of minimal IO.



Source link