Linux is a powerful and versatile operating system used by millions of users worldwide. It's known for its stability, security, and flexibility, making it a popular choice for servers, desktops, and embedded systems. If you're new to Linux, navigating its command-line interface can feel daunting. But fear not, this cheat sheet will equip you with the essential commands to get started and become comfortable using the Linux terminal.
Navigating the Linux File System
1. cd
(Change Directory):
The cd
command is your compass in the Linux file system. It lets you move between directories.
cd /home/user/Documents
: Moves you to the Documents directory within the user's home directory.cd ..
: Moves you one directory level up.cd -
: Takes you back to the previous directory you were in.
2. pwd
(Print Working Directory):
If you're ever unsure where you are in the file system, pwd
will tell you your current location.
pwd
: Prints the absolute path of your current directory.
3. ls
(List Directory Contents):
The ls
command is your window into the contents of any directory.
ls
: Lists the files and directories in the current directory.ls -l
: Lists files with detailed information (permissions, size, owner, etc.).ls -a
: Lists all files, including hidden files (those starting with a dot).
4. mkdir
(Make Directory):
Create new directories to organize your files.
mkdir new_directory
: Creates a new directory named "new_directory".mkdir -p directory1/directory2
: Creates multiple directories recursively.
5. rmdir
(Remove Directory):
Remove empty directories to tidy up your file system.
rmdir directory_name
: Removes the directory "directory_name".
6. touch
(Create Empty File):
Create empty files for various purposes.
touch new_file.txt
: Creates a new empty file named "new_file.txt".
7. cp
(Copy Files):
Copy files to different locations.
cp file.txt /home/user/Documents
: Copies "file.txt" to the user's Documents directory.cp -r directory /new/location
: Copies an entire directory recursively.
8. mv
(Move Files or Rename Files):
Move files between directories or rename them.
mv file.txt /home/user/Downloads
: Moves "file.txt" to the user's Downloads directory.mv old_file.txt new_file.txt
: Renames "old_file.txt" to "new_file.txt".
9. rm
(Remove Files):
Delete files from your system.
rm file.txt
: Deletes the file "file.txt".rm -r directory
: Removes an entire directory recursively. Be careful withrm -r
, as it deletes everything within the directory permanently!
10. find
(Search for Files):
Locate files based on their name, size, or other attributes.
find /home/user -name file.txt
: Searches for a file named "file.txt" in the user's home directory and its subdirectories.
11. grep
(Search for Text within Files):
Search for specific patterns or text within files.
grep "keyword" file.txt
: Finds lines containing "keyword" in "file.txt".
Managing Processes and Services
1. ps
(Process Status):
View a list of running processes.
ps
: Lists current processes running.ps aux
: Provides a more detailed list of processes.
2. top
(System Performance Monitor):
Monitor system performance and CPU usage.
top
: Displays a continuously updated list of processes and system resources.
3. kill
(Terminate Processes):
Forcefully stop processes.
kill -9 process_id
: Sends a SIGKILL signal to the process with the given ID, terminating it immediately.
4. jobs
(List Background Jobs):
View background jobs running in the terminal.
jobs
: Lists the background jobs that are running.
5. fg
(Bring Background Job to Foreground):
Bring a background job to the foreground for interaction.
fg %1
: Brings the first background job to the foreground.
6. bg
(Put Foreground Job to Background):
Move a foreground job to the background.
bg %1
: Sends the first foreground job to the background.
7. service
(Start, Stop, and Restart Services):
Manage system services.
service httpd start
: Starts the Apache HTTP server service.service httpd stop
: Stops the Apache HTTP server service.service httpd restart
: Restarts the Apache HTTP server service.
8. systemctl
(Manage Systemd Services):
Modern Linux distributions use Systemd for service management.
systemctl start httpd
: Starts the Apache HTTP server service.systemctl stop httpd
: Stops the Apache HTTP server service.systemctl restart httpd
: Restarts the Apache HTTP server service.
Working with Files
1. cat
(Concatenate Files):
Display the contents of a file.
cat file.txt
: Displays the contents of "file.txt".cat file1.txt file2.txt > combined.txt
: Combines the contents of "file1.txt" and "file2.txt" into a new file "combined.txt".
2. head
(Display Beginning of File):
Show the first few lines of a file.
head file.txt
: Displays the first 10 lines of "file.txt".head -n 5 file.txt
: Displays the first 5 lines of "file.txt".
3. tail
(Display End of File):
Show the last few lines of a file.
tail file.txt
: Displays the last 10 lines of "file.txt".tail -n 5 file.txt
: Displays the last 5 lines of "file.txt".
4. less
(Page Through Files):
View large files one screen at a time.
less file.txt
: Opens "file.txt" in theless
pager. Use the arrow keys to navigate.
5. more
(Display File One Screen at a Time):
Similar to less
, but less flexible.
more file.txt
: Opens "file.txt" in themore
pager. Press the spacebar to move to the next screen.
6. diff
(Compare Files):
Find differences between two files.
diff file1.txt file2.txt
: Shows the differences between "file1.txt" and "file2.txt".
7. wc
(Word Count):
Count the number of words, lines, and characters in a file.
wc file.txt
: Displays the word count, line count, and character count for "file.txt".
8. sort
(Sort File Contents):
Sort the lines in a file alphabetically or numerically.
sort file.txt
: Sorts the lines in "file.txt" alphabetically.sort -n file.txt
: Sorts the lines in "file.txt" numerically.
9. uniq
(Remove Duplicate Lines):
Remove duplicate lines from a file.
uniq file.txt
: Removes consecutive duplicate lines from "file.txt".
10. sed
(Stream Editor):
Powerful tool for manipulating text streams and files.
sed 's/old/new/g' file.txt
: Replaces all occurrences of "old" with "new" in "file.txt".
11. awk
(Pattern Scanning and Processing Language):
Flexible tool for processing text files.
awk '{print $1}' file.txt
: Prints the first field (column) of each line in "file.txt".
Networking Commands
1. ping
(Check Network Connectivity):
Test if you can reach a specific IP address or hostname.
ping google.com
: Sends ICMP echo requests to "google.com".
2. ifconfig
(Network Interface Configuration):
View information about your network interfaces.
ifconfig
: Displays details about the network interface cards (NICs) on your system.
3. netstat
(Network Status):
View network connections, routing tables, and interface statistics.
netstat -a
: Displays all active network connections and listening ports.
4. ip
(IP Address Management):
A more modern and versatile tool for managing IP addresses and routing.
ip addr show
: Displays IP addresses assigned to network interfaces.
5. traceroute
(Trace Network Path):
Trace the route data takes to a specific host.
traceroute google.com
: Shows the hops data passes through to reach "google.com".
System Information
1. uname
(System Information):
Provides information about the operating system.
uname -a
: Shows the kernel name, host name, release version, machine type, and other information.
2. whoami
(Current User):
Tells you the name of the user currently logged in.
whoami
: Displays the name of the current user.
3. date
(Get Current Date and Time):
Displays the current date and time.
date
: Shows the current date and time.
4. cal
(Display Calendar):
Shows a calendar for a specific month or year.
cal
: Shows the current month's calendar.cal 2024
: Shows the calendar for 2024.
5. uptime
(System Uptime):
Shows how long the system has been running.
uptime
: Displays the system uptime, load average, and number of users logged in.
6. df
(Disk Space):
Displays available disk space on mounted file systems.
df -h
: Shows disk space usage in human-readable format.
7. du
(Disk Usage):
Displays the disk space used by files and directories.
du -h
: Shows disk usage in human-readable format.
8. free
(Memory Usage):
Displays information about free and used memory.
free -h
: Shows memory usage in human-readable format.
9. history
(Command History):
Displays the list of commands you have executed.
history
: Shows the command history.
10. man
(Manual Pages):
Access online documentation for Linux commands.
man ls
: Opens the manual page for thels
command.
Security Commands
1. passwd
(Change Password):
Change the password for your user account.
passwd
: Prompts you to enter and confirm your new password.
2. su
(Switch User):
Switch to a different user account.
su - root
: Switches to the root user account (requires the root password).
3. sudo
(Run Commands as Superuser):
Execute commands with administrative privileges.
sudo apt update
: Updates the software repositories using administrative privileges.
4. id
(User and Group Information):
Display information about your user ID and group memberships.
id
: Shows your user ID, group IDs, and other information.
5. finger
(User Information):
Retrieve information about users on the system.
finger username
: Shows information about the user "username".
6. who
(Logged-In Users):
Lists the users currently logged into the system.
who
: Displays the logged-in users and their terminal information.
7. last
(Login History):
View the history of user logins.
last
: Shows recent logins for all users.
8. w
(System and User Activity):
Displays system load, logged-in users, and their activity.
w
: Shows a summary of system activity, including who's logged in, what they're doing, and the system load.
User Management
1. useradd
(Create New User):
Add new user accounts to the system.
useradd newuser
: Creates a new user named "newuser".
2. userdel
(Delete User):
Remove user accounts from the system.
userdel newuser
: Deletes the user named "newuser".
3. groupadd
(Create New Group):
Create new groups for organizing users.
groupadd newgroup
: Creates a new group named "newgroup".
4. groupdel
(Delete Group):
Remove groups from the system.
groupdel newgroup
: Deletes the group named "newgroup".
5. usermod
(Modify User Account):
Change user account settings.
usermod -G newgroup newuser
: Adds the user "newuser" to the group "newgroup".
6. passwd
(Change User Password):
Change the password for a specific user.
passwd newuser
: Changes the password for the user "newuser".
Software Management
1. apt
(Advanced Packaging Tool):
Manage software packages on Debian-based systems.
apt update
: Updates the package lists from the software repositories.apt upgrade
: Upgrades all installed packages to their latest versions.apt install package_name
: Installs a specific package.apt remove package_name
: Removes a specific package.
2. yum
(Yellowdog Updater, Modified):
Manage software packages on Red Hat-based systems.
yum update
: Updates all installed packages to their latest versions.yum install package_name
: Installs a specific package.yum remove package_name
: Removes a specific package.
3. dnf
(Dandified Yum):
A more modern replacement for yum
on Fedora and Red Hat systems.
dnf update
: Updates all installed packages to their latest versions.dnf install package_name
: Installs a specific package.dnf remove package_name
: Removes a specific package.
4. pacman
(Package Manager):
Manage software packages on Arch Linux systems.
pacman -Syu
: Updates all installed packages to their latest versions.pacman -S package_name
: Installs a specific package.pacman -Rs package_name
: Removes a specific package.
5. dpkg
(Debian Package Manager):
Package management tool for Debian systems.
dpkg -i package_name.deb
: Installs a .deb package.dpkg -r package_name
: Removes a specific package.
6. rpm
(Red Hat Package Manager):
Package management tool for Red Hat-based systems.
rpm -ivh package_name.rpm
: Installs an .rpm package.rpm -e package_name
: Removes a specific package.
Shell Scripting
1. bash
(Bourne Again Shell):
The default shell on most Linux systems.
#!/bin/bash
: The shebang line that indicates the script should be executed by the bash shell.
2. sh
(Bourne Shell):
A legacy shell, still supported but less commonly used.
#!/bin/sh
: The shebang line for the Bourne shell.
3. echo
(Display Text):
Print text to the console.
echo "Hello, world!"
: Displays "Hello, world!" on the screen.
4. read
(Get User Input):
Read user input from the console.
read -p "Enter your name: " name
: Prompts the user to enter their name and stores it in the variablename
.
5. if
(Conditional Statements):
Execute code based on conditions.
if [ condition ]; then
# Code to execute if the condition is true
fi
6. for
(Looping):
Repeat a block of code for each item in a list.
for i in 1 2 3; do
# Code to execute for each value of i
done
7. while
(Looping):
Repeat a block of code as long as a condition is true.
while [ condition ]; do
# Code to execute as long as the condition is true
done
8. case
(Multiple Choice):
Choose different actions based on a value.
case $variable in
value1)
# Code to execute if variable equals value1
;;
value2)
# Code to execute if variable equals value2
;;
*)
# Code to execute if no other case matches
;;
esac
9. exit
(Exit Script):
Terminate the script execution.
exit 0
: Exits the script successfully.exit 1
: Exits the script with an error.
10. sleep
(Pause Execution):
Pause script execution for a specified duration.
sleep 5
: Pauses the script for 5 seconds.
Example Scripts
1. Check Disk Space
#!/bin/bash
df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{print $5 " " $1}'
This script uses df
to get disk space information, filters out irrelevant lines, and then uses awk
to display the percentage used and the filesystem name.
2. List Files Modified in the Past Hour
#!/bin/bash
find . -type f -mmin -60
This script uses find
to search for files modified within the past 60 minutes (one hour).
3. Send an Email Alert
#!/bin/bash
# Set the email address to send the alert to
TO_EMAIL="your_email@example.com"
# Set the email subject
SUBJECT="Server Alert"
# Set the email body
BODY="Something is wrong with the server!"
# Send the email using mail
mail -s "$SUBJECT" "$TO_EMAIL" <<< "$BODY"
This script uses mail
to send an email alert, allowing you to customize the email content.
Conclusion
This Linux commands cheat sheet has covered a broad range of essential commands that will empower you to navigate the Linux command line effectively. As you gain experience, you'll discover more advanced commands and tools, but these foundational commands will provide you with a strong starting point. Remember, practice is key! Experiment with these commands, explore their options, and don't hesitate to consult online resources and forums when you encounter challenges. You'll soon be a confident Linux user, able to manage your files, processes, and system effectively.
FAQs
Q: How do I open a terminal in Linux?
A: To open a terminal in Linux, you can use the following methods:
- Keyboard Shortcut: Press Ctrl+Alt+T or Ctrl+Shift+T (depending on your desktop environment).
- GUI: Click on the "Terminal" icon in your applications menu or launcher.
- Search: Use the search bar in your desktop environment and type "Terminal" or "Command Line."
Q: What is the root user in Linux?
A: The root user is the superuser in Linux, with unrestricted access to the system. It has the highest privileges and can perform any action. Using the root user account requires caution, as errors can have significant consequences.
Q: How do I log in as the root user?
A: To log in as the root user, you can use the su
command:
su - root
This will prompt you for the root password.
Q: What are some resources for learning more about Linux?
A: There are countless resources for learning Linux, including:
- Online Tutorials: Sites like Linux Tutorial, TutorialsPoint, and GeeksforGeeks offer comprehensive tutorials and articles.
- Books: Many excellent books cover Linux, such as "Linux in a Nutshell" and "The Linux Command Line."
- Online Communities: Forums and communities like LinuxQuestions.org and Reddit's /r/linux provide a platform for asking questions and getting help.
Q: How do I get help with a specific command in Linux?
A: To get help with a specific command, use the man
command:
man ls
This will open the manual page for the ls
command, providing detailed information about its usage and options.
Q: What are some basic Linux commands for beginners?
A: Here are some basic Linux commands that are essential for beginners:
ls
: Lists the files and directories in a directory.cd
: Changes the current working directory.pwd
: Prints the current working directory.mkdir
: Creates a new directory.rmdir
: Removes an empty directory.touch
: Creates an empty file.cat
: Displays the contents of a file.man
: Accesses online documentation for commands.
Q: How do I get started with shell scripting?
A: To start with shell scripting, you can begin with the following steps:
- Open a text editor: Use a simple text editor like nano or vim to create a new file.
- Add the shebang line: Start your script with
#!/bin/bash
. - Use basic commands: Include commands like
echo
,read
, andif
to create simple scripts. - Save the script: Save the script with a
.sh
extension. - Make it executable: Use the
chmod
command to make the script executable:chmod +x script.sh
. - Run the script: Execute the script using its name:
./script.sh
.