Basic Linux Commands: Your Starter Guide to the Linux Terminal


13 min read 10-11-2024
Basic Linux Commands: Your Starter Guide to the Linux Terminal

The Linux terminal, often referred to as the command line, is a powerful tool that allows you to interact with your system at a fundamental level. Unlike the graphical user interfaces (GUIs) we're accustomed to, the terminal provides direct access to the operating system's core functions, enabling you to perform tasks with unparalleled efficiency and precision. This article serves as your comprehensive guide to the fundamental Linux commands, empowering you to navigate and manage your Linux environment effectively.

Navigating the File System

The cornerstone of Linux command-line interaction lies in navigating the file system, the hierarchical structure that organizes your files and folders. Let's begin with the command that defines the very heart of Linux navigation: cd.

The 'cd' Command: Changing Directories

Imagine the file system as a vast network of interconnected rooms, each representing a folder, with files residing within them. The cd command acts as your guide, allowing you to move between these rooms. It stands for "change directory." Here's how it works:

  • cd: This takes you to your home directory, the starting point for all your personal files and folders.
  • cd /: This brings you to the root directory, the top of the file system hierarchy, where all other directories originate.
  • cd /home/user: This moves you to the specific user's home directory, replacing "user" with the actual username.
  • cd ..: This shifts you one level up in the directory hierarchy, essentially moving you to the parent directory of your current location.
  • cd folder_name: This takes you directly into the specified folder within your current directory.

The 'ls' Command: Listing Files and Directories

Once you're comfortably navigating the file system, the ls command helps you see what lies within each folder. It stands for "list." Here's how to use it effectively:

  • ls: This lists all files and folders in your current directory.
  • ls -l: This provides a detailed listing, including file permissions, ownership, size, and modification time.
  • ls -a: This displays hidden files (those beginning with a dot '.') in addition to regular files and folders.
  • ls -h: This displays file sizes in a human-readable format, using units like KB, MB, or GB.
  • ls -t: This lists files and folders in reverse chronological order, placing the most recently modified items at the top.

The 'pwd' Command: Finding Your Current Location

Sometimes, when you're deep within the file system, you might forget your current location. That's where the pwd command comes in handy. It stands for "print working directory." This command simply displays the full path of your current location in the file system.

Creating, Editing, and Managing Files

Now that you can navigate the file system, you'll need commands to interact with the files themselves. This section explores the commands for creating, editing, and managing files.

The 'mkdir' Command: Making New Directories

Imagine you're organizing your files, and you need a new room to store them. The mkdir command, short for "make directory," allows you to create new folders within the file system. Here's how to use it:

  • mkdir new_directory: This creates a new directory named "new_directory" within your current location.
  • mkdir -p /path/to/new/directory: This creates a series of directories along the specified path if they don't already exist.

The 'touch' Command: Creating Empty Files

Sometimes you need a blank canvas to start working on. The touch command creates empty files, perfect for writing new content. Here's how to use it:

  • touch new_file.txt: This creates an empty file named "new_file.txt" in your current directory.
  • touch file1.txt file2.txt file3.txt: This creates multiple empty files simultaneously.

The 'cat' Command: Displaying File Contents

Once you have files, you'll want to see what's inside. The cat command, short for "concatenate," displays the contents of a file to your terminal. Here's how to use it:

  • cat file_name.txt: This displays the entire content of "file_name.txt" in the terminal.
  • cat file1.txt file2.txt: This displays the contents of both files consecutively.

The 'echo' Command: Writing Content to Files

The echo command allows you to create simple text files or add content to existing files. Here's how to use it:

  • echo "Hello, world!" > new_file.txt: This creates a new file named "new_file.txt" and writes the text "Hello, world!" into it. The > symbol redirects the output of echo to the file.
  • echo "This is additional text." >> new_file.txt: This adds the text "This is additional text." to the end of the existing "new_file.txt" file. The >> symbol appends the output to the file.

The 'rm' Command: Removing Files and Directories

You may need to clean up your files and folders. The rm command, short for "remove," does just that. Be cautious, as this command permanently deletes files.

  • rm file_name.txt: This deletes the file named "file_name.txt."
  • rm -r directory_name: This recursively deletes the directory "directory_name" and all its contents. The -r option ensures that even subdirectories are deleted.
  • rm -f file_name.txt: This forcefully deletes the file without prompting for confirmation.

The 'mv' Command: Moving and Renaming Files

The mv command, short for "move," allows you to move files from one location to another within the file system. It can also be used to rename files. Here's how to use it:

  • mv file_name.txt /path/to/new/location: This moves the file "file_name.txt" to the specified location.
  • mv file_name.txt new_file_name.txt: This renames the file "file_name.txt" to "new_file_name.txt."

The 'cp' Command: Copying Files

The cp command, short for "copy," allows you to create duplicates of files or directories. Here's how to use it:

  • cp file_name.txt /path/to/new/location: This copies the file "file_name.txt" to the specified location.
  • cp -r directory_name /path/to/new/location: This recursively copies the directory "directory_name" and all its contents to the specified location.

Managing System Processes

Beyond files and directories, the Linux terminal allows you to manage the processes running on your system. These processes represent the ongoing activities taking place within your computer.

The 'ps' Command: Viewing Running Processes

The ps command, short for "process status," allows you to view the processes currently active on your system. Here's how to use it:

  • ps: This displays a brief list of running processes, including their process ID (PID).
  • ps aux: This provides a more detailed list, including the user running each process, its CPU and memory usage, and the command it's executing.
  • ps -ef: This shows a comprehensive list of all processes, including those belonging to other users.

The 'kill' Command: Stopping Processes

Sometimes you need to terminate a running process. The kill command, as its name suggests, allows you to send a signal to a process, potentially stopping it.

  • kill -9 PID: This forcefully terminates the process with the specified PID. The -9 flag sends the SIGKILL signal, which cannot be ignored by the process.

The 'top' Command: Monitoring System Resources

The top command provides a real-time view of your system's resource usage, including CPU activity, memory usage, and running processes. It's a valuable tool for monitoring system performance and identifying potential bottlenecks.

File Permissions and Ownership

In Linux, every file and directory has permissions that control who can access and modify them. This system ensures that users have appropriate access levels and that sensitive data remains secure.

The 'chmod' Command: Changing Permissions

The chmod command, short for "change mode," allows you to modify the permissions of files and directories. Permissions are represented by a three-digit octal number, each digit representing a category:

  • User: The owner of the file or directory.
  • Group: The group that the owner belongs to.
  • Other: Everyone else on the system.

Here's how to interpret the octal number:

  • Read: The r permission allows a user to read the contents of a file.
  • Write: The w permission allows a user to modify the contents of a file.
  • Execute: The x permission allows a user to run a file as a program.

Each digit in the octal number represents the permissions for each category:

  • 4: Read permission
  • 2: Write permission
  • 1: Execute permission

For example, chmod 755 file.txt would set the permissions to:

  • User: Read, write, and execute (7 = 4 + 2 + 1)
  • Group: Read and execute (5 = 4 + 1)
  • Other: Read and execute (5 = 4 + 1)

The 'chown' Command: Changing Ownership

The chown command, short for "change owner," allows you to transfer ownership of files and directories from one user to another.

  • chown new_user:new_group file.txt: This changes the ownership of "file.txt" to the user "new_user" and the group "new_group."

Working with Text Files

The Linux terminal offers a wealth of commands for manipulating text files, making it ideal for editing, searching, and transforming text data.

The 'grep' Command: Searching for Text

The grep command, short for "global regular expression print," is a powerful tool for searching for specific patterns within text files.

  • grep "pattern" file_name.txt: This searches for the specified pattern within "file_name.txt" and displays all lines containing the pattern.

The 'sed' Command: Editing Text

The sed command, short for "stream editor," allows you to perform various text editing operations on files, such as replacing text, deleting lines, and inserting text.

  • sed 's/old_pattern/new_pattern/g' file_name.txt: This replaces all occurrences of "old_pattern" with "new_pattern" within "file_name.txt."

The 'sort' Command: Sorting Data

The sort command arranges the lines of a text file in a specific order.

  • sort file_name.txt: This sorts the lines of "file_name.txt" alphabetically in ascending order.
  • sort -r file_name.txt: This sorts the lines in reverse alphabetical order (descending).
  • sort -n file_name.txt: This sorts the lines numerically.

The 'uniq' Command: Removing Duplicate Lines

The uniq command removes consecutive duplicate lines from a text file.

  • uniq file_name.txt: This removes consecutive duplicate lines from "file_name.txt."

The 'head' Command: Displaying the Beginning of a File

The head command displays the first few lines of a file.

  • head -n 10 file_name.txt: This displays the first 10 lines of "file_name.txt."

The 'tail' Command: Displaying the End of a File

The tail command displays the last few lines of a file.

  • tail -n 5 file_name.txt: This displays the last 5 lines of "file_name.txt."

Using Pipes and Redirections

Pipes and redirections are powerful techniques that allow you to combine multiple commands together, forming complex workflows.

Pipes (|)

Pipes connect the output of one command as the input to another.

  • ls -l | grep "file_name.txt": This first lists all files and folders using ls -l, then searches for lines containing "file_name.txt" using grep.

Redirections (>, >>)

Redirections control the output of commands, directing it to files or other destinations.

  • ls -l > output.txt: This redirects the output of ls -l to a file named "output.txt."
  • date >> output.txt: This appends the output of date to the existing file "output.txt."

Shell Scripts

Shell scripts are small programs written in a scripting language, such as Bash, that automate tasks and sequences of commands. They can be used to perform repetitive operations, streamline complex workflows, and customize your Linux experience.

Creating a Shell Script

You can create a shell script using a text editor, saving it with the .sh extension. For example, create a file named my_script.sh and add the following lines:

#!/bin/bash
echo "Hello, world!"
date

The first line (#!/bin/bash) tells the system to execute the script using the Bash interpreter.

Making the Script Executable

To run the script, you need to make it executable:

chmod +x my_script.sh

Running the Script

To execute the script, use the following command:

./my_script.sh

Networking

Linux offers powerful tools for managing and interacting with networks.

The 'ifconfig' Command: Network Configuration

The ifconfig command displays network interface configuration information, including IP addresses, MAC addresses, and network masks.

  • ifconfig: This displays the configuration of all network interfaces on your system.
  • ifconfig eth0: This displays the configuration of the network interface named "eth0."

The 'ping' Command: Network Connectivity Testing

The ping command sends ICMP echo request packets to a specified host and waits for responses. This allows you to test network connectivity and measure round-trip time (RTT).

  • ping google.com: This sends ping requests to the Google server and displays the results.

The 'netstat' Command: Network Statistics

The netstat command provides various network statistics, including active connections, listening ports, routing tables, and network interfaces.

  • netstat -a: This displays information about all active connections and listening ports.
  • netstat -r: This displays the current routing table.

The 'traceroute' Command: Network Path Tracing

The traceroute command traces the path that network packets take to a destination host, identifying the intermediate routers along the way. This helps diagnose network problems and identify potential bottlenecks.

  • traceroute google.com: This traces the path from your system to the Google server.

System Information

The Linux terminal provides a wealth of commands to gather information about your system's hardware and software.

The 'uname' Command: System Information

The uname command provides information about your system's operating system, architecture, and kernel version.

  • uname -a: This displays detailed system information, including the operating system name, kernel version, architecture, hostname, and other details.
  • uname -r: This displays the kernel version.
  • uname -m: This displays the system's hardware architecture.

The 'free' Command: Memory Usage

The free command displays the amount of free and used memory on your system, including both physical RAM and swap space.

  • free -m: This displays memory usage information in megabytes.

The 'df' Command: Disk Usage

The df command displays the amount of disk space used and available on mounted file systems.

  • df -h: This displays disk usage information in a human-readable format, using units like MB or GB.

The 'date' Command: Date and Time

The date command displays the current date and time.

  • date: This displays the current date and time.
  • date +%Y-%m-%d: This displays the date in the format "YYYY-MM-DD."
  • date +%H:%M:%S: This displays the time in the format "HH:MM:SS."

System Administration

The Linux terminal empowers you to manage and configure your system at a granular level.

The 'apt' Command: Package Management (Debian-based Systems)

The apt command is used for managing software packages on Debian-based Linux distributions, such as Ubuntu and Debian.

  • apt update: This updates the package lists, ensuring you have the latest information about available packages.
  • apt upgrade: This upgrades all installed packages to their latest versions.
  • apt install package_name: This installs the specified package.
  • apt remove package_name: This removes the specified package.

The 'yum' Command: Package Management (Red Hat-based Systems)

The yum command is used for managing software packages on Red Hat-based Linux distributions, such as CentOS and Fedora.

  • yum update: This updates the package lists and upgrades installed packages.
  • yum install package_name: This installs the specified package.
  • yum remove package_name: This removes the specified package.

The 'systemctl' Command: Systemd Service Management

The systemctl command is used to manage services in systemd-based Linux distributions.

  • systemctl status service_name: This displays the status of the specified service.
  • systemctl start service_name: This starts the specified service.
  • systemctl stop service_name: This stops the specified service.
  • systemctl restart service_name: This restarts the specified service.
  • systemctl enable service_name: This enables the service to start automatically at boot time.
  • systemctl disable service_name: This disables the service from starting automatically at boot time.

Troubleshooting

The Linux terminal provides several commands to help you diagnose and troubleshoot system problems.

The 'dmesg' Command: Kernel Log Messages

The dmesg command displays the kernel ring buffer, containing messages generated by the kernel, including error messages, warnings, and informational messages.

  • dmesg: This displays the kernel ring buffer.

The 'journalctl' Command: System Log Messages

The journalctl command is used to access and manage the system journal, which contains log messages from various system components, including kernel, services, and applications.

  • journalctl -r: This displays the system journal, starting with the latest entries.

The 'lsof' Command: Open Files and Ports

The lsof command lists all open files and ports on your system, indicating which processes are using them. This helps identify resource conflicts and debug network problems.

  • lsof -i: This lists all open files and ports.

The 'strace' Command: System Call Tracing

The strace command traces the system calls made by a process, providing detailed information about its interactions with the kernel. This is a valuable tool for debugging system problems and understanding process behavior.

  • strace command: This traces the system calls made by the specified command.

Security

Linux offers a robust set of commands for managing security and user accounts.

The 'passwd' Command: Changing Passwords

The passwd command allows you to change your own password or set a new password for another user.

  • passwd: This prompts you to change your own password.
  • sudo passwd user_name: This allows you to change the password for the specified user, requiring root privileges.

The 'useradd' Command: Adding Users

The useradd command creates a new user account on your system.

  • useradd user_name: This creates a new user account named "user_name."

The 'userdel' Command: Removing Users

The userdel command deletes a user account from your system.

  • userdel user_name: This deletes the user account named "user_name."

The 'groups' Command: Viewing Group Memberships

The groups command displays the groups that a user belongs to.

  • groups user_name: This lists the groups that the specified user is a member of.

The 'su' Command: Switching Users

The su command allows you to temporarily switch to a different user account.

  • su user_name: This switches to the user account named "user_name," prompting for the user's password.

The 'sudo' Command: Running Commands with Elevated Privileges

The sudo command allows you to execute commands with root privileges, providing a secure and controlled way to elevate your permissions.

  • sudo command: This runs the specified command with root privileges, prompting for your password.

Conclusion

The Linux terminal is a versatile and powerful tool for interacting with your system, empowering you to manage files, run programs, monitor resources, and much more. By mastering these basic commands, you unlock the full potential of the Linux environment, gaining a deeper understanding of your system and expanding your capabilities as a Linux user.

FAQs

1. What is the difference between a command and a script?

A command is a single instruction that you type into the terminal. For example, ls is a command that lists files and folders. A script is a series of commands that are combined together in a file, allowing you to automate a task or a series of tasks.

2. How do I get help on a specific command?

The man command (short for "manual") provides a comprehensive manual page for any command. Simply type man command_name to access the documentation for that command.

3. How can I run a command in the background?

You can append an ampersand (&) to the end of any command to run it in the background. For example, ls -l & will run ls -l in the background, allowing you to continue using the terminal while the command executes.

4. How do I copy text from the terminal?

You can use the Ctrl+Shift+C keyboard shortcut to copy text from the terminal, and Ctrl+Shift+V to paste text.

5. Where can I find more resources for learning Linux commands?

There are many excellent resources available online for learning Linux commands. Some popular options include:

These resources offer comprehensive tutorials, articles, and examples to help you deepen your understanding of Linux commands and explore advanced topics.