- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
Ever SSH'd into an EC2 instance and felt like you'd landed on an alien planet? That blinking cursor in the terminal can be intimidating, especially when critical systems depend on your next keystroke. But here's the secret: Linux isn't just the operating system underneath a vast majority of AWS services; it's the language of the cloud. Mastering its command line interface (CLI) is no longer optional—it's a superpower for any serious cloud professional, developer, or DevOps engineer.
In today's cloud-native world, whether you're managing fleets of EC2 instances, debugging containers in EKS or ECS, or diving deep into serverless logs, a solid grasp of Linux commands is your key to efficiency, control, and faster problem-solving. This post isn't just another list; it's your practical guide to the 20 most crucial Linux commands, packed with examples, real-world scenarios, and pro-tips to elevate your skills from novice to ninja. Let's tame that terminal together!
Table of Contents
In an era of sophisticated GUIs and Infrastructure as Code, why bother with the command line? Simple: efficiency, automation, and direct control.
Linux is the undisputed king of server operating systems. Statistics consistently show that the vast majority of public cloud instances (think AWS EC2, Azure VMs, Google Compute Engine) run Linux. Services like Amazon EKS, ECS, and even AWS Lambda (under the hood for custom runtimes) rely heavily on Linux environments.
When you need to:
Think of the Graphical User Interface (GUI) as a pre-set menu in a restaurant. It's user-friendly but offers limited options. The Command Line Interface (CLI), on the other hand, is like having a direct conversation with the chef. You can ask for exactly what you want, how you want it.
When you type a command, you're interacting with a program called the shell (most commonly Bash - Bourne Again SHell). The basic structure of a command is:
command [options] [arguments]
Understanding this simple structure is the first step to demystifying the terminal.
The Essential 20: Linux Commands You Can't Live Without
Let's dive into the commands that will form the bedrock of your Linux toolkit. We'll cover what they do, common use cases, and basic syntax.
Navigating Your File System
These commands are your map and compass in the Linux directory structure.
Once you can navigate, you'll need to work with files.
* **Pro Tip:** Alias `rm` to `rm -i` (interactive) in your `.bashrc` for an extra safety net.
Searching for Files and Content
Finding what you need is crucial.
Security starts with proper file permissions.
Keep an eye on your server's health.
Control what's running on your system.
Sometimes, you need elevated privileges.
* Important: Use sudo responsibly. "With great power comes great responsibility."
Real-World Scenario: Troubleshooting a Slow EC2 Instance
Imagine your web application hosted on an EC2 instance suddenly becomes sluggish. Users are complaining! Here's how these commands can help you diagnose:
By systematically using these commands, you can often pinpoint the root cause of the slowdown, whether it's a runaway process, a full disk, or an application error spewing logs.
Common Blunders: Linux Command Pitfalls to Avoid
With great power comes the potential for great mistakes. Here are a few common pitfalls:
Level Up: Pro Tips for Command-Line Mastery
Beyond individual commands, the true power of the Linux CLI comes from combining them and using shell features:
We've covered 20 foundational Linux commands, but this is just the beginning. Mastering the Linux command line is an ongoing journey, one that dramatically enhances your effectiveness in any cloud environment, especially AWS. These commands are your building blocks for scripting, automation, troubleshooting, and gaining a deeper understanding of your systems.
Don't just read about them—practice! Spin up an EC2 t2.micro instance (it's in the AWS Free Tier!) and start experimenting. The more you use these commands, the more intuitive they'll become.
Further Learning Resources:
Phew, that was a lot, but hopefully, you're feeling more confident about tackling the Linux terminal! These 20 commands are your launchpad.
What are your go-to Linux commands or tricks that I missed? Share your favorites in the comments below! Your insights could help someone else level up.
If this post helped you untangle the command line or gave you a new trick to try:
Thanks for reading, and happy commanding!
In today's cloud-native world, whether you're managing fleets of EC2 instances, debugging containers in EKS or ECS, or diving deep into serverless logs, a solid grasp of Linux commands is your key to efficiency, control, and faster problem-solving. This post isn't just another list; it's your practical guide to the 20 most crucial Linux commands, packed with examples, real-world scenarios, and pro-tips to elevate your skills from novice to ninja. Let's tame that terminal together!
Table of Contents
- Why Linux Commands Still Reign Supreme in the Cloud
- The Linux CLI: Your Direct Line to the Server
- The Essential 20: Linux Commands You Can't Live Without
- Navigating Your File System
- Viewing and Manipulating Files
- Searching for Files and Content
- Managing Permissions
- Monitoring System Resources
- Process Management
- Executing with Superpowers
- Real-World Scenario: Troubleshooting a Slow EC2 Instance
- Common Blunders: Linux Command Pitfalls to Avoid
- Level Up: Pro Tips for Command-Line Mastery
- Conclusion: Your Journey to Linux CLI Wizardry
- Ready to Command the Cloud?
In an era of sophisticated GUIs and Infrastructure as Code, why bother with the command line? Simple: efficiency, automation, and direct control.
Linux is the undisputed king of server operating systems. Statistics consistently show that the vast majority of public cloud instances (think AWS EC2, Azure VMs, Google Compute Engine) run Linux. Services like Amazon EKS, ECS, and even AWS Lambda (under the hood for custom runtimes) rely heavily on Linux environments.
When you need to:
- Quickly diagnose a problem on a remote server.
- Automate repetitive tasks with shell scripts.
- Access environments where a GUI isn't available (common in CI/CD pipelines or minimal server installs).
- Perform fine-grained operations not exposed by a console. The Linux CLI is your most powerful ally. It's lightweight, scriptable, and offers unparalleled access to the system's internals.
Think of the Graphical User Interface (GUI) as a pre-set menu in a restaurant. It's user-friendly but offers limited options. The Command Line Interface (CLI), on the other hand, is like having a direct conversation with the chef. You can ask for exactly what you want, how you want it.
When you type a command, you're interacting with a program called the shell (most commonly Bash - Bourne Again SHell). The basic structure of a command is:
command [options] [arguments]
- Command: The program you want to run (e.g., ls, cp).
- Options (or flags): Modify the command's behavior (e.g., ls -l for a long listing). They usually start with a hyphen (-) or double hyphen (--).
- Arguments: What the command acts upon (e.g., a file name, a directory path).
Understanding this simple structure is the first step to demystifying the terminal.
The Essential 20: Linux Commands You Can't Live Without
Let's dive into the commands that will form the bedrock of your Linux toolkit. We'll cover what they do, common use cases, and basic syntax.
Navigating Your File System
These commands are your map and compass in the Linux directory structure.
pwd (Print Working Directory)
- What it does: Shows you the full path of the directory you are currently in.
- Use case: Essential for orientation, especially when your prompt doesn't show the full path.
Example:
pwd
# Output: /home/ec2-user/my-project
ls (List Directory Contents)
- What it does: Lists files and directories within the current (or specified) directory.
- Use case: See what's in a folder.
- Common options:
- -l: Long format (shows permissions, owner, size, modification date).
- -a: Show all files, including hidden ones (starting with .).
- -h: Human-readable sizes (e.g., 1K, 2M).
Example:
ls -lah
# Output:
# total 12K
# drwxr-xr-x 2 ec2-user ec2-user 4.0K May 17 10:00 .
# drwxr-xr-x 3 root root 4.0K May 16 09:00 ..
# -rw-r--r-- 1 ec2-user ec2-user 512 May 17 10:00 config.txt
# .rw-r--r-- 1 ec2-user ec2-user 128 May 17 10:00 .env
cd (Change Directory)
- What it does: Moves you to a different directory.
- Use case: Navigate the file system.
- Special arguments:
- cd ~ or cd: Go to your home directory.
- cd ..: Go up one directory level.
- cd -: Go to the previous directory you were in.
Example:
cd /var/log
pwd
# Output: /var/log
cd ..
pwd
# Output: /var
mkdir (Make Directory)
- What it does: Creates a new directory.
- Use case: Organize your files.
- Common option: -p: Create parent directories if they don't exist.
Example:
mkdir my_new_app
mkdir -p project/src/assets
Once you can navigate, you'll need to work with files.
cp (Copy)
- What it does: Copies files or directories.
- Use case: Duplicate files, create backups.
- Common option: -r (or -R): Recursive copy, for directories.
Example:
cp source.txt destination.txt
cp -r my_app_v1/ my_app_v2_backup/
mv (Move/Rename)
- What it does: Moves files or directories, or renames them.
- Use case: Relocate files, rename files.
Example:
mv old_name.txt new_name.txt # Rename
mv important_file.doc /secure_location/ # Move
rm (Remove)
- What it does: Deletes files or directories. Use with extreme caution!
- Use case: Clean up unwanted files.
- Common options:
- -r: Recursive, for directories.
- -f: Force, suppresses confirmations (dangerous!).
Example:
rm temp_file.tmp
rm -r old_project/ # Be careful!
* **Pro Tip:** Alias `rm` to `rm -i` (interactive) in your `.bashrc` for an extra safety net.
cat (Concatenate and Display)
- What it does: Displays the content of files, or concatenates multiple files.
- Use case: Quickly view small files, combine text files.
Example:
cat config.yml
cat part1.txt part2.txt > combined.txt
less (View File Content Paginated)
- What it does: Allows you to view large files page by page. More powerful than cat for large files.
- Use case: Read log files, long configuration files.
- Navigation within less:
- Spacebar / f: Forward one page.
- b: Backward one page.
- /pattern: Search for pattern.
- q: Quit.
Example:
less /var/log/syslog
head (Output First Part of Files)
- What it does: Displays the beginning of a file.
- Use case: Quickly check the start of a log or data file.
- Common option: -n <number>: Show specified number of lines (default is 10).
Example:
head access.log
head -n 5 server.conf
tail (Output Last Part of Files)
- What it does: Displays the end of a file.
- Use case: Monitor real-time log updates.
- Common options:
- -n <number>: Show specified number of lines (default is 10).
- -f: Follow; output appended data as the file grows (essential for logs!).
Example:
tail error.log
tail -n 50 application.log
tail -f /var/log/nginx/access.log
Searching for Files and Content
Finding what you need is crucial.
grep (Global Regular Expression Print)
- What it does: Searches text using patterns (regular expressions). Incredibly powerful.
- Use case: Find specific lines in files, filter command output.
- Common options:
- -i: Case-insensitive search.
- -r or -R: Recursive search in directories.
- -l: List filenames containing the pattern.
- -v: Invert match (show lines that don't match).
- -C <num>: Context (show num lines before and after match).
Example:
grep "ERROR" application.log
grep -irl "api_key" /etc/
ps aux | grep nginx # Filter process list for nginx
find (Find Files)
- What it does: Searches for files in a directory hierarchy based on various criteria (name, type, size, modification time, etc.).
- Use case: Locate files when you don't know the exact path.
- Common expressions:
- -name "filename": Find by name (supports wildcards like *.log).
- -type f: Find files only.
- -type d: Find directories only.
- -mtime -7: Modified in the last 7 days.
- -exec command {} \;: Execute a command on found files.
Example:
find /var/www -name "*.php"
find . -type f -name "*.tmp" -delete # Find and delete temp files
find /home/ec2-user -mtime +30 -size +1G -ls # Find files older than 30 days and larger than 1GB
Security starts with proper file permissions.
chmod (Change Mode)
- What it does: Changes the permissions of files and directories.
- Use case: Control who can read, write, or execute files.
- Modes:
- Numeric: e.g., 755 (owner:rwx, group:r-x, others:r-x).
- Symbolic: e.g., u+x (add execute permission for user), go-w (remove write for group and others).
Example:
chmod 700 private_key.pem # Only owner can read/write
chmod +x script.sh # Make script executable
chmod -R 644 /var/www/html/* # Set read for all, write for owner on web files
chown (Change Owner)
- What it does: Changes the owner and group of files and directories.
- Use case: Transfer ownership, often needed after extracting archives or for web server configurations.
- Common option: -R: Recursive for directories.
- Syntax: chown user:group filename
Example:
sudo chown www-data:www-data /var/www/html/index.html
sudo chown -R ec2-user:ec2-user /app/code
Keep an eye on your server's health.
df (Disk Free)
- What it does: Reports file system disk space usage.
- Use case: Check available disk space.
- Common option: -h: Human-readable format.
Example:
df -h
# Output:
# Filesystem Size Used Avail Use% Mounted on
# /dev/xvda1 8.0G 3.5G 4.5G 44% /
# tmpfs 488M 0 488M 0% /dev/shm
du (Disk Usage)
- What it does: Estimates file and directory space usage.
- Use case: Find out what's consuming disk space.
- Common options:
- -h: Human-readable format.
- -s: Summary (total size only).
- -d <depth> or --max-depth=<depth>: Show usage for directories up to a certain depth.
Example:
du -sh /var/log/* # Show sizes of items in /var/log
du -h --max-depth=1 /opt # Show sizes of directories directly under /opt
Control what's running on your system.
ps (Process Status)
- What it does: Reports a snapshot of the current processes.
- Use case: See what programs are running.
- Common options (often combined):
- aux: Show all processes for all users in a user-friendly format.
- ef: Show all processes in full format.
Example:
ps aux
ps aux | grep httpd # Find processes related to httpd
top / htop (Table of Processes)
- What it does: Displays Linux processes in real-time. htop is an enhanced, more user-friendly version (often needs to be installed: sudo apt install htop or sudo yum install htop).
- Use case: Monitor CPU/memory usage, identify resource-hungry processes.
- Interactive commands in top/htop: (e.g., k to kill, s to sort by CPU/Memory).
Example:
top
htop # If installed
Sometimes, you need elevated privileges.
sudo (Superuser Do)
- What it does: Allows a permitted user to execute a command as the superuser (root) or another user.
- Use case: Perform administrative tasks like installing software, editing system files, managing services.
Example:
sudo apt update
sudo systemctl restart nginx
sudo nano /etc/hosts
* Important: Use sudo responsibly. "With great power comes great responsibility."
Real-World Scenario: Troubleshooting a Slow EC2 Instance
Imagine your web application hosted on an EC2 instance suddenly becomes sluggish. Users are complaining! Here's how these commands can help you diagnose:
SSH into the instance:
ssh ec2-user@your-instance-ip -i your-key.pem
Check system load and resource usage with top (or htop):
top
Look for high CPU usage, low available memory, or high load average. Note any suspicious processes.
Check disk space with df -h:
df -h
Is a partition full (especially / or /var)? This can cripple a system.
If disk space is an issue, find large files/directories with du:
sudo du -sh /var/log/* # Check log sizes
sudo du -h --max-depth=1 /opt | sort -hr # Find largest directories in /opt
Check for specific problematic processes with ps and grep:
ps aux | grep 'java' # If it's a Java app
ps aux | grep 'apache2' # Or Apache
Examine relevant log files with tail -f:
tail -f /var/log/nginx/error.log
tail -n 100 /var/log/app/my-app.log | grep "FATAL"
Look for recent errors or unusual activity.
Check network connections (if applicable, netstat or ss might be needed):
sudo netstat -tulnp | grep LISTEN # See listening ports and processes
# or modern equivalent:
sudo ss -tulnp | grep LISTEN
This can help identify if your application is listening on the correct port or if there are too many connections.
By systematically using these commands, you can often pinpoint the root cause of the slowdown, whether it's a runaway process, a full disk, or an application error spewing logs.
Common Blunders: Linux Command Pitfalls to Avoid
With great power comes the potential for great mistakes. Here are a few common pitfalls:
- The infamous rm -rf /: Never, ever run this unless you intend to wipe your entire system. The -r means recursive, and -f means force. Starting from / (the root directory) means everything.
- chmod 777 everywhere: Giving read, write, and execute permissions to everyone for every file is a massive security risk. Understand permission needs and apply the principle of least privilege.
- Forgetting sudo: Many system-level commands require root privileges. If a command fails with "Permission denied," you likely forgot sudo. Conversely, don't use sudo for everyday tasks that don't require it.
- Accidental Overwrites with Redirection: command > file.txt overwrites file.txt. If you want to append, use command >> file.txt.
- Spaces in Filenames: While Linux supports spaces in filenames, they can be tricky on the command line. Either escape them (My\ Document.txt) or quote the filename ("My Document.txt"). It's often easier to avoid spaces.
- Piping to the Wrong Command: Understand what each command in a pipe | does. A misplaced command can lead to unexpected (and sometimes destructive) results.
Level Up: Pro Tips for Command-Line Mastery
Beyond individual commands, the true power of the Linux CLI comes from combining them and using shell features:
Piping (|): Send the output of one command as input to another.
ls -l | grep ".txt" # List only .txt files
ps aux | grep 'nginx' | awk '{print $2}' # Get PIDs of nginx processes
Redirection (>, >>, <):
- >: Redirect standard output to a file (overwrite).
- >>: Append standard output to a file.
- <: Redirect standard input from a file.
- 2>: Redirect standard error.
- 2>&1: Redirect standard error to standard output.
ls -l /etc > etc_contents.txt
echo "New log entry" >> app.log
my_script.sh > output.log 2>&1 # Capture both stdout and stderr
Command Chaining (&&, ||):
- command1 && command2: Run command2 only if command1 succeeds.
- command1 || command2: Run command2 only if command1 fails.
sudo apt update && sudo apt upgrade -y
make || echo "Build failed!"
Command Substitution (`command` or $(command)): Use the output of one command as an argument to another.
echo "Today is $(date)"
# Remove all Docker containers
docker rm $(docker ps -aq)
Aliases: Create shortcuts for long commands in your ~/.bashrc or ~/.zshrc.
alias ll='ls -alhF'
alias update='sudo apt update && sudo apt upgrade -y'
# After adding, source the file: source ~/.bashrc
History (history, Ctrl+R):
- history: Show command history.
- !number: Execute command number from history.
- !!: Execute the last command.
- Ctrl+R: Reverse search through history.
xargs: Build and execute command lines from standard input. Useful with find.
find . -name "*.log" -type f -print0 | xargs -0 rm -f # Safely delete found log files
awk and sed: Powerful text processing utilities. While complex, even basic usage can be a game-changer for manipulating text data on the fly. (A topic for a future deep dive!)
We've covered 20 foundational Linux commands, but this is just the beginning. Mastering the Linux command line is an ongoing journey, one that dramatically enhances your effectiveness in any cloud environment, especially AWS. These commands are your building blocks for scripting, automation, troubleshooting, and gaining a deeper understanding of your systems.
Don't just read about them—practice! Spin up an EC2 t2.micro instance (it's in the AWS Free Tier!) and start experimenting. The more you use these commands, the more intuitive they'll become.
Further Learning Resources:
- Man Pages: For any command, type man <command_name> (e.g., man ls) to get the official manual page.
- (A fantastic free book)
- Consider certifications like LFCS (Linux Foundation Certified SysAdmin) or RHCSA (Red Hat Certified System Administrator) if you want to go deep.
Phew, that was a lot, but hopefully, you're feeling more confident about tackling the Linux terminal! These 20 commands are your launchpad.
What are your go-to Linux commands or tricks that I missed? Share your favorites in the comments below! Your insights could help someone else level up.
If this post helped you untangle the command line or gave you a new trick to try:
- ? Follow me here on Dev.to for more practical AWS, Cloud, and DevOps content.
- ? Leave a comment with your thoughts, questions, or your own favorite Linux commands.
- ? Bookmark this post for easy reference.
- ? Let's connect on ! I'm always happy to chat about cloud and tech.
Thanks for reading, and happy commanding!