Software Lab Simulation 21-2: Linux Commands
trychec
Oct 29, 2025 · 15 min read
Table of Contents
Navigating the Linux operating system efficiently hinges on mastering its command-line interface. The power and flexibility that Linux offers become truly accessible through its extensive array of commands, allowing users to interact with the system at a granular level. This guide delves into essential Linux commands, providing a foundation for both beginners and those seeking to deepen their Linux proficiency.
Essential Linux Commands: Your Gateway to the System
Linux commands are instructions given to the operating system through the terminal, enabling users to perform tasks ranging from basic file management to complex system administration. Understanding these commands is vital for anyone working with Linux, whether on a personal computer, server, or embedded system.
File and Directory Management
-
ls(list): Displays the files and directories in the current directory. Options include-l(long listing format),-a(show hidden files), and-h(human-readable sizes).- Example:
ls -lhadisplays all files (including hidden ones) in a detailed format with file sizes in a more readable format (e.g., KB, MB, GB).
- Example:
-
cd(change directory): Navigates to a specified directory. Usecd ..to move up one directory level, andcd ~to return to the home directory.- Example:
cd /var/logchanges the current directory to the/var/logdirectory.
- Example:
-
pwd(print working directory): Shows the absolute path of the current directory.- Example:
pwdmight output/home/user/documents.
- Example:
-
mkdir(make directory): Creates a new directory. The-poption creates parent directories if they don't exist.- Example:
mkdir -p /home/user/documents/new_foldercreates the directorynew_folderand its parent directories if they are missing.
- Example:
-
rmdir(remove directory): Deletes an empty directory.- Example:
rmdir empty_folderremoves the directory namedempty_folder, but only if it is empty.
- Example:
-
rm(remove): Deletes files. Use-rto remove directories recursively, and-fto force removal without prompting. Use with caution!- Example:
rm -rf unwanted_folderforcefully removes the directoryunwanted_folderand all its contents.
- Example:
-
cp(copy): Copies files and directories. The-roption is used to copy directories recursively.- Example:
cp -r source_folder destination_foldercopies the directorysource_folderand all its contents todestination_folder.
- Example:
-
mv(move): Moves or renames files and directories.- Example:
mv old_file.txt new_file.txtrenames the fileold_file.txttonew_file.txt. - Example:
mv file.txt /home/user/documents/moves the filefile.txtto the/home/user/documents/directory.
- Example:
-
touch: Creates an empty file or updates the timestamp of an existing file.- Example:
touch new_file.txtcreates an empty file namednew_file.txt.
- Example:
File Content Manipulation
-
cat(concatenate): Displays the content of a file.- Example:
cat file.txtdisplays the entire content offile.txtin the terminal.
- Example:
-
less: Displays the content of a file one page at a time, allowing for navigation.- Example:
less large_file.txtallows you to scroll throughlarge_file.txtusing the arrow keys.
- Example:
-
head: Displays the first few lines of a file (default: 10 lines). Use-nto specify the number of lines.- Example:
head -n 20 file.txtdisplays the first 20 lines offile.txt.
- Example:
-
tail: Displays the last few lines of a file (default: 10 lines). Use-nto specify the number of lines. The-foption follows the file and displays new lines as they are added.- Example:
tail -f log_file.txtdisplays the last 10 lines oflog_file.txtand continues to display new lines as they are written to the file.
- Example:
-
echo: Displays a line of text. Useful for displaying variables or writing to a file using redirection.- Example:
echo "Hello, world!"displays "Hello, world!" in the terminal. - Example:
echo "This is a test" > file.txtoverwritesfile.txtwith the text "This is a test". - Example:
echo "This is a test" >> file.txtappends the text "This is a test" tofile.txt.
- Example:
-
grep(global regular expression print): Searches for a pattern in a file or input stream.- Example:
grep "error" log_file.txtsearches for lines containing the word "error" inlog_file.txt. - Example:
grep -i "error" log_file.txtperforms a case-insensitive search. - Example:
grep -v "error" log_file.txtdisplays lines that do not contain the word "error".
- Example:
-
sed(stream editor): A powerful tool for text manipulation. It can be used to find and replace text, delete lines, and more.- Example:
sed 's/old_text/new_text/g' file.txtreplaces all occurrences of "old_text" with "new_text" infile.txt. Thegflag indicates global replacement. - Example:
sed '/pattern/d' file.txtdeletes all lines containing the "pattern" fromfile.txt. Note: This only outputs the modified content to the terminal. Usesed -i 's/old/new/g' file.txtto modify the file in-place.
- Example:
-
awk: Another powerful text processing tool. It's often used for extracting and manipulating data from structured files.- Example:
awk '{print $1}' file.txtprints the first field of each line infile.txt, assuming fields are separated by spaces. - Example:
awk -F',' '{print $2}' file.csvprints the second field of each line infile.csv, where fields are separated by commas.
- Example:
User and Permissions Management
-
whoami: Displays the current username.- Example:
whoamimight output "user".
- Example:
-
sudo(super user do): Executes a command with administrative privileges.- Example:
sudo apt updateupdates the package list using administrative privileges.
- Example:
-
passwd: Changes the user's password.- Example:
passwdprompts the user for their current password and then the new password.
- Example:
-
chmod(change mode): Modifies file permissions. Permissions are typically represented in octal notation (e.g., 755) or symbolic notation (e.g.,u+rwx,g+rx,o+rx).- Example:
chmod 755 file.txtsets the permissions offile.txtto read, write, and execute for the owner, read and execute for the group, and read and execute for others. - Example:
chmod u+x file.txtadds execute permission for the owner offile.txt.
- Example:
-
chown(change owner): Changes the owner and group of a file or directory.- Example:
chown user:group file.txtchanges the owner offile.txttouserand the group togroup.
- Example:
-
chgrp(change group): Changes the group ownership of a file or directory.- Example:
chgrp group file.txtchanges the group ownership offile.txttogroup.
- Example:
Process Management
-
ps(process status): Displays a snapshot of the current processes. Options include-aux(show all processes for all users) and-ef(full format listing).- Example:
ps auxdisplays all running processes with detailed information.
- Example:
-
top: Displays a dynamic real-time view of running processes, showing CPU and memory usage.- Example: Simply running
topin the terminal provides a continuously updated view of system processes.
- Example: Simply running
-
kill: Sends a signal to a process, usually to terminate it. You need the process ID (PID) to use this command. The default signal is TERM (terminate). Usekill -9 <PID>for a forceful kill (SIGKILL), but use it as a last resort.- Example:
kill 1234sends the TERM signal to the process with PID 1234. - Example:
kill -9 1234forcefully terminates the process with PID 1234.
- Example:
-
killall: Kills processes by name.- Example:
killall firefoxkills all processes named "firefox".
- Example:
-
bg(background): Moves a process to the background.- Example: After suspending a process with Ctrl+Z, use
bgto resume it in the background.
- Example: After suspending a process with Ctrl+Z, use
-
fg(foreground): Moves a process to the foreground.- Example:
fgbrings the most recently backgrounded process to the foreground. You can specify a job number (e.g.,fg %1) to bring a specific background process forward.
- Example:
-
jobs: Lists the currently running background processes.- Example:
jobsdisplays a list of backgrounded jobs with their job numbers and status.
- Example:
Networking
-
ifconfig(interface configuration): Displays network interface information. Deprecated in some distributions; useipinstead.- Example:
ifconfigshows the IP address, MAC address, and other details for each network interface.
- Example:
-
ip: A more modern replacement forifconfig. Provides more comprehensive networking tools.- Example:
ip addrdisplays IP addresses. - Example:
ip routedisplays the routing table. - Example:
ip linkshows network interface details.
- Example:
-
ping: Tests network connectivity by sending ICMP echo requests to a specified host.- Example:
ping google.comsends ping requests to Google's server.
- Example:
-
netstat(network statistics): Displays network connections, routing tables, interface statistics, and more. Also being replaced byssin some distributions.- Example:
netstat -anshows all active network connections. - Example:
netstat -plntushows listening TCP and UDP ports along with the process ID and name.
- Example:
-
ss(socket statistics): A more modern and faster tool for displaying network socket information.- Example:
ss -lntushows listening TCP and UDP ports. - Example:
ss -anshows all active network connections.
- Example:
-
ssh(secure shell): Establishes a secure connection to a remote server.- Example:
ssh user@remote_serverconnects to the remote server as the user "user".
- Example:
-
scp(secure copy): Securely copies files between a local and a remote system, or between two remote systems.- Example:
scp file.txt user@remote_server:/path/to/destination/copiesfile.txtto the specified directory on the remote server.
- Example:
-
wget(web get): Downloads files from the internet.- Example:
wget https://example.com/file.zipdownloadsfile.zipfrom the specified URL.
- Example:
-
curl: Transfers data to or from a server, supporting various protocols (HTTP, FTP, etc.). It is more versatile thanwget.- Example:
curl https://example.comretrieves the HTML content of the specified webpage. - Example:
curl -O https://example.com/file.zipdownloadsfile.zipfrom the specified URL (similar towget).
- Example:
-
traceroute: Traces the route packets take to reach a destination.- Example:
traceroute google.comshows the path packets take to reach Google's server.
- Example:
-
nslookup(name server lookup): Queries DNS (Domain Name System) servers to obtain domain name or IP address mapping information.
* Example: `nslookup google.com` finds the IP address associated with the domain name google.com
System Information and Utilities
-
uname: Displays system information, such as kernel name, version, and architecture.- Example:
uname -adisplays all system information.
- Example:
-
df(disk free): Shows disk space usage. The-hoption displays sizes in a human-readable format.- Example:
df -hdisplays disk space usage in KB, MB, GB, etc.
- Example:
-
du(disk usage): Shows disk space usage of files and directories. The-hoption displays sizes in a human-readable format, and-sprovides a summary.- Example:
du -hs /home/user/documentsdisplays the total disk space used by the/home/user/documentsdirectory and its contents.
- Example:
-
free: Displays memory usage. The-hoption displays sizes in a human-readable format.- Example:
free -hdisplays memory usage in KB, MB, GB, etc.
- Example:
-
uptime: Shows how long the system has been running, along with the average load.- Example:
uptimemight output something like:10:30:00 up 2 days, 5:10, 1 user, load average: 0.10, 0.15, 0.12
- Example:
-
date: Displays the current date and time.- Example:
datedisplays the current date and time.
- Example:
-
cal(calendar): Displays a calendar.- Example:
caldisplays the current month's calendar. - Example:
cal 2024displays the calendar for the year 2024.
- Example:
-
history: Displays a list of previously executed commands.- Example:
historyshows your command history. Use!nto execute the nth command in your history (e.g.,!100to execute the 100th command). Use!!to execute the previous command.
- Example:
-
man(manual): Displays the manual page for a command.- Example:
man lsdisplays the manual page for thelscommand.
- Example:
-
info: Another way to access documentation for commands. Often provides more detailed information thanman.- Example:
info lsdisplays the info page for thelscommand.
- Example:
-
locate: Finds files by name. Requires a pre-built database; update it withsudo updatedb.- Example:
locate file.txtfinds all files namedfile.txt.
- Example:
-
find: A more powerful file-finding utility. Can search based on various criteria (name, size, modification time, permissions, etc.).- Example:
find /home/user -name "file.txt"searches forfile.txtwithin the/home/userdirectory and its subdirectories. - Example:
find . -type f -size +1Mfinds all files larger than 1MB in the current directory and its subdirectories. - Example:
find . -mtime -7finds all files modified within the last 7 days.
- Example:
-
which: Locates the executable file associated with a command.- Example:
which lsmight output/usr/bin/ls.
- Example:
-
whereis: Locates the binary, source, and manual page files for a command.- Example:
whereis lsmight outputls: /usr/bin/ls /usr/share/man/man1/ls.1.gz
- Example:
Package Management (Examples for Debian/Ubuntu and Red Hat/CentOS)
-
Debian/Ubuntu (APT - Advanced Package Tool):
sudo apt update: Updates the package list.sudo apt upgrade: Upgrades installed packages.sudo apt install package_name: Installs a package.sudo apt remove package_name: Removes a package.sudo apt purge package_name: Removes a package and its configuration files.apt search keyword: Searches for packages containing the specified keyword.apt show package_name: Displays detailed information about a package.
-
Red Hat/CentOS (YUM - Yellowdog Updater, Modified / DNF - Dandified YUM):
sudo yum update: Updates all installed packages. (YUM is older, DNF is newer and often preferred)sudo dnf update: Updates all installed packages (preferred on newer systems).sudo yum install package_name: Installs a package.sudo dnf install package_name: Installs a package (preferred on newer systems).sudo yum remove package_name: Removes a package.sudo dnf remove package_name: Removes a package (preferred on newer systems).yum search keyword: Searches for packages containing the specified keyword.dnf search keyword: Searches for packages containing the specified keyword (preferred on newer systems).yum info package_name: Displays detailed information about a package.dnf info package_name: Displays detailed information about a package (preferred on newer systems).
Command Chaining and Redirection
-
Piping (
|): Sends the output of one command as the input to another command.- Example:
ls -l | grep "file.txt"lists all files in the current directory and then filters the output to only show lines containing "file.txt".
- Example:
-
Redirection (
>,>>): Redirects the output of a command to a file.>overwrites the file, while>>appends to the file.- Example:
ls -l > file_list.txtsaves the output ofls -lto the filefile_list.txt, overwriting any existing content. - Example:
echo "New entry" >> log_file.txtappends the text "New entry" to the filelog_file.txt.
- Example:
-
Input Redirection (
<): Redirects the input of a command from a file.- Example:
wc -l < file.txtcounts the number of lines infile.txt.
- Example:
-
Semicolon (
;): Executes multiple commands sequentially, regardless of whether the previous command succeeded or failed.- Example:
cd /home/user; ls -lchanges the directory to/home/userand then lists the files in that directory.
- Example:
-
AND Operator (
&&): Executes the second command only if the first command succeeds (returns an exit code of 0).- Example:
mkdir new_dir && cd new_dircreates the directorynew_dirand then changes the directory tonew_dironly if themkdircommand was successful.
- Example:
-
OR Operator (
||): Executes the second command only if the first command fails (returns a non-zero exit code).- Example:
rm file.txt || echo "File not found"attempts to removefile.txtand, if it fails (because the file doesn't exist), prints "File not found".
- Example:
Shell Scripting Basics
While a full discussion of shell scripting is beyond the scope of this article, it's important to understand that Linux commands can be combined into scripts to automate complex tasks. A shell script is simply a text file containing a series of commands that are executed in sequence.
-
Creating a Script: Use a text editor (like
nano,vim, orgedit) to create a file (e.g.,my_script.sh). -
Shebang (
#!): The first line of a shell script should typically be the shebang line, which specifies the interpreter to use (usually#!/bin/bashfor Bash scripts). -
Example Script:
#!/bin/bash # This is a simple shell script. echo "Starting the script..." # Create a directory mkdir my_directory # Change to the directory cd my_directory # Create a file touch my_file.txt echo "Script finished." -
Making a Script Executable: Use
chmod +x my_script.shto make the script executable. -
Running a Script: Execute the script with
./my_script.sh.
Tips for Mastering Linux Commands
- Practice Regularly: The best way to learn Linux commands is to use them regularly. Experiment with different commands and options.
- Use the Manual Pages: The
mancommand is your best friend. Consult it whenever you are unsure about a command's usage. - Take Notes: Keep a notebook or digital document to record useful commands and examples.
- Search Online: When you encounter a problem, search online for solutions. Many online resources, forums, and tutorials can help you.
- Experiment in a Safe Environment: Use a virtual machine or a non-production environment to experiment with commands without risking your primary system.
- Start with the Basics: Don't try to learn everything at once. Start with the essential commands and gradually expand your knowledge.
- Understand Command Syntax: Pay attention to the syntax of commands, including options and arguments.
- Learn Regular Expressions: Regular expressions are powerful tools for pattern matching and text manipulation. Learning them will significantly enhance your ability to use commands like
grep,sed, andawk.
Common Mistakes to Avoid
- Using
rm -rfcarelessly: This command can permanently delete files and directories without prompting. Double-check your target before executing it. - Incorrectly using wildcards: Wildcards like
*and?can match multiple files. Be careful when using them with commands likermorcp. - Forgetting
sudowhen needed: Some commands require administrative privileges. Remember to usesudowhen necessary. - Not understanding file permissions: Incorrect file permissions can lead to security vulnerabilities or prevent programs from running correctly.
- Running untrusted scripts: Only execute scripts from trusted sources. Malicious scripts can damage your system.
- Not backing up your data: Regularly back up your important data to protect against data loss.
Advanced Concepts
- Regular Expressions: Mastering regular expressions (regex) is crucial for advanced text processing. Regex allows you to define complex search patterns for use with
grep,sed,awk, and other tools. - Bash Scripting: Learn to write more complex shell scripts to automate system administration tasks, software deployment, and more.
- Systemd: Understand
systemd, the system and service manager for Linux. Learn how to manage services, view logs, and configure system settings. - SELinux/AppArmor: Learn about security-enhancing technologies like SELinux and AppArmor, which provide mandatory access control for processes.
- Containers (Docker, Podman): Explore containerization technologies, which allow you to package and run applications in isolated environments.
Conclusion
The Linux command line is a powerful tool that allows you to interact with your system in a precise and efficient way. By mastering essential Linux commands and practicing regularly, you can become a proficient Linux user and unlock the full potential of the operating system. This guide provides a solid foundation for your Linux journey. Remember to explore, experiment, and continue learning to expand your knowledge and skills.
Latest Posts
Related Post
Thank you for visiting our website which covers about Software Lab Simulation 21-2: Linux Commands . We hope the information provided has been useful to you. Feel free to contact us if you have any questions or need further assistance. See you next time and don't miss to bookmark.