Best Linux One Liners
Here is a collection of my favourite Linux one-liners. Linux is such a versatile operating system that you can string commands consecutively to make a command that perfectly fits your requirements.
Print Login Session Information
Find the last users who have logged onto your system.
last | head -n 20 | awk 'NF { sessions[$1 " " $3 " " $4 " " $5]++ } END { for (session in sessions) print sessions[session], session }'
Let’s break down the command step by step:
- last: This command shows a list of the most recent login sessions on the system.
- |: This symbol is a pipe that takes the output of the command on its left and uses it as input for the command on its right.
- grep -v “^$”: This command, when combined with
last
, filters out blank lines from the output.grep -v
is used to select lines that do not match a specific pattern, in this case,^$
, which represents an empty line. - awk ‘{ print $1 }’: After filtering out the blank lines,
awk
is used to print only the first column of the output. By default,awk
separates columns by whitespace, so$1
refers to the first column. - sort -nr: This command sorts the output numerically (
-n
) in reverse order (-r
). It sorts the login session information in descending order based on the numerical values in the first column. - uniq -c: Finally,
uniq -c
displays unique lines from the sorted input and counts the occurrences of each line. In this case, it counts the number of occurrences of each login session in the sorted list.
You should see output similar to this:
1 reboot boot 6.5.0-28-generic Wed
1 rbailey tty2 Thu May
2 reboot boot 6.5.0-28-generic Fri
3 rbailey tty2 Sun May
1 rbailey tty2 Tue Apr
2 rbailey tty2 Fri May
2 rbailey tty2 Tue May
3 reboot boot 6.5.0-28-generic Sun
3 reboot boot 6.5.0-28-generic Tue
1 rbailey tty2 Wed May
1 reboot boot 6.5.0-28-generic Thu
So, in summary, the command sequence fetches the login session information, filters out blank lines, extracts the first column (presumably usernames or session IDs), sorts them in descending numerical order, and then counts the occurrences of each unique login session.
Set a console clock in the Terminal
I stumbled upon this amazing one-liner. Credit to the original website: betterprogramming.pub
while sleep 1; do
tput sc;
tput cup 0 $(tput cols); # Move to row 0, last column
tput cuf -29; # Move 29 characters to the left
date;
tput rc;
done &
Here’s what each part of the command does:
while sleep 1; do ... done &
: This starts a loop that repeats the commands inside it every second (sleep 1
) in the background (&
). It continuously executes the commands within the loop, updating the information displayed on the screen.tput sc
:tput sc
saves the current cursor position. It remembers where the cursor is before it moves it.tput cup 0 $(($(tput cols)-29))
:tput cup
moves the cursor to a specified position on the terminal screen. In this case, it moves the cursor to the top line (0
) and calculates the column position by subtracting 29 from the total number of columns (tput cols
). This position is used to display the output of thedate
command.date
: This command prints the current date and time to the specified location on the terminal screen.tput rc
:tput rc
restores the saved cursor position to where it was previously saved (tput sc
). After printing the date, this command brings the cursor back to its original position before thetput sc
.
Overall, this command creates a continuously updating display of the current date and time on the terminal screen, positioned at the top right corner (approximately 29 columns from the right edge) while preserving the cursor’s original position elsewhere on the screen.
List the Largest directories on your Computer
sudo du -h --max-depth=1 / | sort -hr
Let’s break down the components of this command:
sudo
: This command is used to execute subsequent commands with elevated privileges, often requiring administrator permissions.du -h --max-depth=1 /
: Thedu
command stands for “disk usage” and is used to estimate file and directory space usage. In this case:-h
flag stands for “human-readable,” displaying file sizes in a format that is easier for humans to understand, such as KB, MB, GB, etc.--max-depth=1
sets the maximum depth to 1, restricting the output to only the immediate directories and their sizes within the specified path, which is the root directory/
.
|
: This is the pipe operator, which takes the output of the command on its left and uses it as input for the command on its right. It allows chaining multiple commands together.sort -hr
: This part of the command sorts the output received fromdu
in reverse numerical (-n
) order and in a human-readable (-h
) format. The flags used here are:-h
: Sort human-readable numbers (e.g., 2K, 1G).-r
: Reverse the result of comparisons, displaying the largest sizes first.
Example Output:
77G /
46G /home
11G /snap
8.4G /usr
8.3G /var
2.6G /installables
1014M /opt
349M /boot
15M /etc
8.8M /tmp
So, when executed, this command essentially lists the sizes of directories within the root directory, displaying them in human-readable format and sorting them in descending order based on their sizes. This can be very helpful for identifying large directories and their sizes, aiding in disk space management and understanding where the storage is being utilized the most.
Get Important System Information
This awesome one-liner pulls out lots of important information about your local machine
echo -e "System Info:
- Hostname: $(hostname)
- Current User: $(whoami)
- CPU: $(grep 'model name' /proc/cpuinfo | uniq | sed 's/model name\s*:\s*//')
- RAM: $(free -h | awk '/^Mem/ {print $2}')
- Disks: $(lsblk | grep -c disk)
- Last Reboot: $(who -b | awk '{print $3, $4}')
- Power On Time: $(uptime -p)
- Current Date and Time: $(date '+%Y-%m-%d %H:%M:%S')
- OS: $(lsb_release -d | cut -f2-)"
Let’s break it down step by step:
echo -e
: This command is used to print the following text, and the-e
flag enables the interpretation of backslash escapes."System Info: ... OS: "
: This is a string that serves as the header for the system information.$(hostname)
: Prints the current system’s hostname.$(whoami)
: Prints the username of the current user.$(grep 'model name' /proc/cpuinfo | uniq | sed 's/model name\s*:\s*//')
: Retrieves the CPU model information by searching the/proc/cpuinfo
file, then removes duplicate lines usinguniq
, and finally usessed
to remove the “model name” label.$(free -h | awk '/^Mem/ {print $2}')
: Displays the total RAM by using thefree
command to show memory usage in a human-readable format (-h
), andawk
is used to print the second column of the line starting with “Mem,” which represents the total memory.$(lsblk | grep -c disk)
: Counts the number of disks by listing block devices withlsblk
and counting the lines containing the word “disk” usinggrep -c
.$(who -b | awk '{print $3, $4}')
: Shows the last reboot time by using thewho
command with the-b
flag to display the system boot time.awk
is then used to print the third and fourth columns.$(uptime -p)
: Prints the system’s uptime in a human-readable format.$(date '+%Y-%m-%d %H:%M:%S')
: Displays the current date and time in the specified format.$(lsb_release -d | cut -f2-)
: Retrieves the operating system description usinglsb_release
and extracts the second field onwards usingcut
.
You should see output like this:
System Info:
- Hostname: laptop-richard-bailey
- Current User: rbailey
- CPU: 12th Gen Intel(R) Core(TM) i7-1260P
- RAM: 31Gi
- Disks: 2
- Last Reboot: 2024-05-28 09:16
- Power On Time: up 3 days, 49 minutes
- Current Date and Time: 2024-05-31 10:05:18
- OS: Ubuntu 22.04.4 LTS
The entire command combines these components to produce a comprehensive system information summary with details about the hostname, current user, CPU, RAM, disks, last reboot, power-on time, current date and time, and the operating system.
Journalctl Command to Filter and Count Error Messages
journalctl
is a utility in Linux systems for querying and displaying logs from the systemd journal. When managing virtual environments like VMware, it can be helpful to scan logs for error messages to identify potential issues. The command presented here searches for error-related entries in the systemd journal and counts how many times each executable generated an error message, all formatted neatly for analysis.
journalctl --no-pager --since today \
--grep 'fail|error|fatal' --output json|jq '._EXE' | \
sort | uniq -c | sort --numeric --reverse --key 1
Command Explanation
journalctl --no-pager --since today --grep 'fail|error|fatal' --output json|jq '._EXE' | sort | uniq -c | sort --numeric --reverse --key 1
:journalctl --no-pager --since today
: Thejournalctl
command fetches logs from the systemd journal. The--no-pager
flag prevents the output from being piped into a pager likeless
. The--since today
parameter limits the search to logs generated since the beginning of the current day.--grep 'fail|error|fatal'
: This flag filters the logs to only include entries containing the terms “fail,” “error,” or “fatal.”--output json
: Outputs the filtered logs in JSON format.jq '._EXE'
: Thejq
command parses the JSON output to extract the value of the_EXE
key, which represents the executable that generated the log entry.sort
: Sorts the extracted executable names.uniq -c
: Counts the occurrences of each unique executable name.sort --numeric --reverse --key 1
: Finally, sorts the count and executable name in descending order, making it easy to identify which executables are generating the most error messages.
Here is my example output:
31 "/usr/lib/slack/slack"
12 "/usr/bin/cat"
7 "/snap/remmina/6419/usr/bin/remmina"
2 "/usr/libexec/fprintd"
2 null
1 "/usr/libexec/gsd-color"
1 "/usr/bin/gnome-shell"
1 "/snap/snapd/21759/usr/lib/snapd/snapd"
Thanks for taking the time to read this article. if you have any questions or feedback, please write in the comment section below.
Recent Comments