Here are my top 8 advanced shell commands, with practical examples to up your terminal game, I hope they’re as useful to you as they are to me.
1. grep
– Search for patterns in files or output
Example: Search for the word “error” in log files.
grep "error" /var/log/syslog
Search recursively for a pattern in all files within a directory:
grep -r "TODO" /path/to/codebase/
2. awk
– Process and analyze text data
Example: Print the second column from a file with space-separated values:
awk '{print $2}' data.txt
Extract and summarize disk usage from the df
command:
df -h | awk '{print $5 " " $1}'
3. sed
– Stream editor for modifying files or input
Example: Replace the word “cat” with “dog” in a file called animals.txt:
sed 's/cat/dog/g' animals.txt
Delete lines containing a specific word, in this case “error”:
sed '/error/d' logfile.txt
4. xargs
– Pass output as arguments to another command
Example: Delete all files that has extension .log
in the current directory (Use this very carefully)!:
find . -name "*.log" | xargs rm
Or, if filenames contain spaces:
find . -name "*.log" -print0 | xargs -0 rm
5. find
– Search for files based on criteria
Example: Find all .txt
files modified in the last 7 days:
find /path/to/dir -name "*.txt" -mtime -7
Find files larger than 100MB:
find /path/to/dir -type f -size +100M
6. rsync
– Efficient file synchronization
Example: Sync a local directory to a remote server:
rsync -avz /local/dir/ user@remote:/remote/dir/
Sync while excluding specific files:
rsync -avz --exclude '*.tmp' /local/dir/ user@remote:/remote/dir/
7. tmux
– Terminal multiplexer for managing multiple sessions
Example: Start a new tmux
session:
tmux new -s mysession
Detach from the session without killing it:
Ctrl + b, then d
Reattach to the session later:
tmux attach -t mysession
8. lsof
– List open files and processes using them
Example: List all open files on the system:
lsof
Find out which process is using a specific port (e.g., port 8080):
lsof -i :8080
Identify files opened by a specific user:
lsof -u username
In Conclusion
Think of it as a journey rather than a destination.
I started small (and you should too), experimenting with just a couple of commands that seemed useful for my projects. Before long, I was stringing commands together, automating processes I never thought possible. It was like having a superpower! I can’t stress enough how important it is to practice and find what works best for you.
If you find these commands helpful. I will keep adding more