Master Linux Shell Tricks: Formatting Output, Loops, Sorting, and Powerful Xargs
This guide shows how to format command output with column, repeat commands until they succeed, sort processes by CPU or memory, re‑run the previous command with sudo, and leverage xargs for batch operations, all with clear examples and code snippets.
1. Output formatting
For commands whose output is hard to read, such as mount, you can pipe the result to column -t to align columns. mount | column -t Similarly, the content of files like /etc/passwd can be formatted by specifying a delimiter:
cat /etc/passwd | column -t -s:2. Repeat command until success
You can use an infinite while true loop to keep trying a command until it succeeds, for example pinging a server until it is live:
while true
do
ping -c 1 baidu.com > /dev/null 2>&1 && break
done;The redirection >/dev/null 2>&1 discards both standard output and error.
3. Sort process list by CPU or memory
The ps aux output shows CPU usage in column 3 and memory usage in column 4.
Sort by memory (column 4):
ps aux | sort -rnk 4Sort by CPU (column 3):
ps aux | sort -rnk 34. Execute the previous command with root privileges
If you forget to prepend sudo to a command that requires root, you can re‑run the last command with sudo !!:
[vagrant@localhost ~]$ cat /etc/shadow
cat: /etc/shadow: Permission deniedRunning: sudo !! will execute cat /etc/shadow as root.
5. Powerful Xargs command
Example (1)
Given a file urls.txt containing a list of URLs, you can download them all with a single pipeline:
cat urls.txt | xargs wget xargstakes the output of cat and passes each line as an argument to wget.
Example (2)
To kill all tomcat processes:
ps -ax | grep tomcat | grep -v grep | awk '{print $1}' | xargs kill -9 grep tomcatselects lines containing “tomcat”, grep -v grep excludes the grep process itself, awk '{print $1}' extracts the PID column, and xargs kill -9 terminates those PIDs.
Example (3)
If the target command needs multiple arguments, such as copying files, you can use xargs -i to substitute each input line: ls *.txt | xargs -i cp {} /tmp This copies every *.txt file to /tmp.
Click “Read original” to view the full article list.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
