Many Linux users have experienced a lasting sense of accomplishment after composing a particularly clever command that achieves multiple actions in just one line or that manages to do in one line what usually takes 10 clicks and as many windows in a graphical user interface (GUI). Aside from being the stuff of legend, one-liners are great examples of why the terminal is considered to be such a powerful tool.
By the end of this article, you will have:
- A list of 20 commands that will make your tasks easier when working on Linux
- An understanding of the possibilities of combining simple commands to create more powerful commands
- More fun than you might expect running these commands
Without any specific order of importance, these are our top 20 one-liners for the Linux terminal. Although we've divided some of the longer commands with the \ symbol for easier readability, you can enter them all on a single line in your terminal because, after all, they are one-liners.
1. Apply a command on files with different names
The shell {} operator is great for this. Here's an example with three directories enclosed in {}:
$ mkdir -p -v /home/josevnz/tmp/{dir1,anotherdir,similardir}2. Edit a file in place
Do you want to replace a string on one or more files without using an editor? Sure, sed to the rescue:
$ sed -i 's#ORIGINAL_VALLUE#NEW_VALUE#g' myfile1 myfile2But wait, Perl lovers will tell you they can do the same:
$ perl -p -i -e 's#ORIGINAL#NEW_VALUE#' myfile1 myfile23. Share a file quickly using a web server
Raise your hand if you haven't used this at least once to share a directory quickly:
$ cd $mydir && python3 -m http.server 88884. Find failures with journalctl
Sometimes things break. You can find the most recent errors using a combination of journalctl, along with the classic tools sort and uniq:
$ journalctl --no-pager --since today \
--grep 'fail|error|fatal' --output json|jq '._EXE' | \
sort | uniq -c | sort --numeric --reverse --key 1
898172 "/usr/bin/dockerd"
752 "/usr/local/sbin/node_exporter"
30 "/usr/bin/gnome-shell"
26 "/usr/bin/cat"
22 "/usr/libexec/gsd-media-keys"
[...]In this case, it seems that the Docker daemon is unhappy.
[ Download this eBook to get ready for your Red Hat remote exam. ]
5. Make a backup via encrypted file transfer
Use ssh and tar to make secure backups. They go together like peanut butter and jelly:
$ tar --create --directory /home/josevnz/tmp/ --file - *| \
ssh raspberrypi "tar --directory /home/josevnz \
--verbose --list --file -"You can add flavor to the backup job with compression and encryption—just like adding ingredients to your sandwich.
6. Write instantaneous files
This is a great trick when you need to write multiline documents:
$ cat<<DOC>/my/new/file
Line1
Line2
A $VARIABLE
DOCYou can also just cat > file, and when you are done editing, just input the EOF character (Ctrl+D):
[josevnz@dmaf5 temp]$ cat > testfile
This is a test
multiple lines
and here we go
[josevnz@dmaf5 temp]$ 7. Search for a file, and include some extensions and exclude others
This example uses the grep way to search for specific files. It's pretty fast and easy to remember:
$ grep -R 'import' --include='*.java' --color MySourceCodeDirOr you can try the find way (use xargs to handle a large number of matches properly):
$ find MySourceCodeDir/ -name '*.java' -type f -print| xargs \
grep --color 'importWhy find, you may ask? You can combine find with -exec to execute actions on your files first and then pass the results to the filter. The processing possibilities are endless here.
8. Monitor memory without top or htop
This one is almost cheating. It repeats a command, such as free, every five seconds and highlights the differences:
$ watch -n 5 -d '/bin/free -m'9. Display disk partition sizes
Use lsbk (list block) and jq (to manipulate a JSON on the command line) to display partition information:
$ lsblk --json | jq -c '.blockdevices[]|[.name,.size]'
["loop0","55.5M"]
["loop1","156M"]
["loop2","32.3M"]
["zram0","4G"]
["nvme0n1","476.9G"]10. Quickly display a file type
The What is function is called with wi. It quickly tells you a file's type.
To check a single file:
$ function wi { test -n "$1" && stat --printf "%F\n" "$1"; }To check multiple files:
$ function wi { test "$#" -gt 0 && stat --printf "%n: %F\n" "$@"; }NOTE: Functions are superior and can do the same work as an alias.
11. Display the size of an installed RPM
If you have an RPM-based system, sooner or later, you will format your queries. Here's an example:
$ rpm --queryformat='%12{SIZE} %{NAME}\n' \
-q java-11-openjdk-headless[ Train and test on our latest courses and exams from Red Hat Training & Certification: Red Hat Enterprise Linux skills path. ]
12. Display the total size of a group of files
In this case, the find command acts as a filter, displays the size of each file in bytes, and finally, shows the total size:
$ t=0; for n in $(find ~/Documents -type f -name '*.py' -print | xargs \
stat --printf "%s "); do ((t+=n)); done; echo $tOr, if you want a function (better), try this approach:
$ function size { t=0; test -d "$1" && for n in $(find $1 \
-type f -name '*.py' -print| \
xargs stat --printf "%s "); do ((t+=n)); done; echo $t; }
size $mydir13. Update all Git repositories on a directory
You already know how useful Git is. Here's a trick to be more efficient with your updates:
$ for i in */.git; do cd $(dirname $i); git pull; cd ..; done14. Expose a web directory using containers
Containers are critical today. This one-liner exposes a directory via Podman:
$ podman run --rm -v .:/usr/share/nginx/html:ro,Z \
-p 30080:80 -d nginx15. Check the weather
Use this function to find out whether you need a jacket today:
weather() { curl -s --connect-timeout 3 -m 5 http://wttr.in/$1; }16. Display the top 10 IP addresses hitting a webserver
Here's a task web admins may use frequently with Nginx (it may also work with Apache) to grab the top 10 internet protocol addresses hitting a webserver from the access log:
$ cat /var/log/nginx/access.log | cut -f 1 -d ' ' | sort | \
uniq -c | sort -hr | head -n 1017. Round floats in Bash with Python's help
You can do pretty cool stuff with Python, but this example just rounds numbers:
$ echo "22.67892" | python3 -c "print(f'{round(float(input()))}')"
2318. Run a mini calculator
This function defines a quick calculator on the command line with variable precision (the default is 2). It uses bc. Create the function like this:
$ function qqbc() { echo "scale=${2:-2}; $1" | bc -lNext, perform a quick calculation:
$ qqbc "2/3"
.66In case you need additional precision, just define a second parameter:
$ qqbc "2/3" 4
.6666This tool is called qqbc because it's an improvement on the old function qbc.
19. Convert a CSV to JSON
This trick is a modification of this popular recipe to convert CSV files to the JSON format:
$ python3 -c \
"import csv,json,sys;print(json.dumps(list(csv.reader(open(sys.argv[1])))))" \
covid19-vaccinations-town-age-grp.csv20. Install and run commands with Docker
If you have Docker installed and you want to run a command without installing a bunch of dependencies on your system (while doing a quick run), this may be all you need:
$ docker run --rm --interactive curlimages/curl curl \
--verbose --location --fail --silent --output - \
https://example.comThe command runs the latest version of curl from a container, and later removes it. Notice that the command ends with a dash (-), which tells curl to output to your terminal. The possibilities are endless here.
Wrap up
The ability to build powerful combinations of simple commands is one of the reasons Unix and Linux are so popular.
Fortunately. it is not difficult to learn these one-liners. Focus on remembering what a simple command does, and then think about how you can mix many simple commands to make a powerful recipe.
Always check the man page or use the info command to figure out what else the tool can do. You may be surprised to learn that one tool can do everything without combining it with another utility.
There are many sites on the internet with plenty of one-line examples. We hope these examples will lead you to write better one-liners of your own.
About the authors
Proud dad and husband, software developer and sysadmin. Recreational runner and geek.
Anthony Critelli is a Linux systems engineer with interests in automation, containerization, tracing, and performance. He started his professional career as a network engineer and eventually made the switch to the Linux systems side of IT. He holds a B.S. and an M.S. from the Rochester Institute of Technology.
Ricardo Gerardi is a Principal Consultant at Red Hat, having transitioned from his previous role as a Technical Community Advocate for Enable Sysadmin. He's been at Red Hat since 2018, specializing in IT automation using Ansible and OpenShift.
With over 25 years of industry experience and 20+ years as a Linux and open source enthusiast and contributor, Ricardo is passionate about technology. He is particularly interested in hacking with the Go programming language and is the author of Powerful Command-Line Applications in Go and Automate Your Home Using Go. Ricardo also writes regularly for Red Hat and other blogs, covering topics like Linux, Vim, Ansible, Containers, Kubernetes, and command-line applications.
Outside of work, Ricardo enjoys spending time with his daughters, reading science fiction books, and playing video games.
Roberto Nozaki (RHCSA/RHCE/RHCA) is an Automation Principal Consultant at Red Hat Canada where he specializes in IT automation with Ansible. He has experience in the financial, retail, and telecommunications sectors, having performed different roles in his career, from programming in mainframe environments to delivering IBM/Tivoli and Netcool products as a pre-sales and post-sales consultant.
Roberto has been a computer and software programming enthusiast for over 35 years. He is currently interested in hacking what he considers to be the ultimate hardware and software: our bodies and our minds.
Roberto lives in Toronto, and when he is not studying and working with Linux and Ansible, he likes to meditate, play the electric guitar, and research neuroscience, altered states of consciousness, biohacking, and spirituality.
More like this
File encryption and decryption made easy with GPG
From maintenance to enablement: Making your platform a force-multiplier
Python's Tale | Command Line Heroes
Testing, PDFs, And Donkeys | Compiler: Stack/Unstuck
Browse by channel
Automation
The latest on IT automation for tech, teams, and environments
Artificial intelligence
Updates on the platforms that free customers to run AI workloads anywhere
Open hybrid cloud
Explore how we build a more flexible future with hybrid cloud
Security
The latest on how we reduce risks across environments and technologies
Edge computing
Updates on the platforms that simplify operations at the edge
Infrastructure
The latest on the world’s leading enterprise Linux platform
Applications
Inside our solutions to the toughest application challenges
Virtualization
The future of enterprise virtualization for your workloads on-premise or across clouds