dotlinux guide

A Step-by-Step Guide to Using the Linux Command Line

The Linux command line (CLI) is a powerful interface that allows users to interact with the operating system through text-based commands. While graphical user interfaces (GUIs) are user-friendly, the CLI offers unparalleled efficiency, automation capabilities, and control—making it indispensable for developers, system administrators, and power users. Whether you’re managing servers, automating tasks, or debugging issues, mastering the CLI is a foundational skill. This guide will walk you through the fundamentals, essential commands, advanced techniques, and best practices to help you navigate and utilize the Linux command line with confidence.

Table of Contents

What is the Linux Command Line?

The Linux command line, also known as the shell, is a text-based interface that interprets user input and communicates with the operating system kernel. Unlike GUIs, which rely on clicks and menus, the CLI uses commands to execute tasks. The most common shell is Bash (Bourne Again Shell), preinstalled on most Linux distributions and macOS. Other shells (e.g., Zsh, Fish) offer enhanced features but follow similar core principles.

Why use the CLI?

  • Speed: Execute complex tasks with a few keystrokes (e.g., bulk file renaming).
  • Automation: Script repetitive tasks (e.g., backups, log analysis).
  • Remote Access: Manage servers via SSH (no GUI required).
  • Precision: Fine-grained control over system operations.

Getting Started: Accessing the Terminal

To use the CLI, you need a terminal emulator—a program that displays the shell. Here’s how to open it on common systems:

Linux Desktop

  • Ubuntu/Debian: Press Ctrl + Alt + T or search for “Terminal” in the applications menu.
  • Fedora/RHEL: Press Super (Windows key) + T or search for “Terminal”.

macOS

  • Open Spotlight (Cmd + Space), type Terminal, and press Enter.

Remote Access (Servers)

Use SSH to connect to remote Linux servers:

ssh username@server-ip-address  # Example: ssh [email protected]

Once open, you’ll see a prompt like:

john@ubuntu:~$  # Format: [username]@[hostname]:[current-directory]$

The $ indicates a regular user prompt; # indicates a root (administrator) prompt.

Fundamental Concepts

Command Syntax

Most Linux commands follow this structure:

command [options] [arguments]
  • Command: The action to perform (e.g., ls, cd).
  • Options: Modify the command’s behavior (e.g., -l for “long format” in ls -l). Short options use - (e.g., -a), long options use -- (e.g., --all).
  • Arguments: Targets for the command (e.g., filenames, directories).

Key Terminology

  • Shell: The program that interprets commands (e.g., Bash).
  • Path: The location of a file/directory (e.g., /home/john/documents/report.txt).
    • Absolute Path: Full path from the root directory (/), e.g., /home/john/file.txt.
    • Relative Path: Path relative to the current directory, e.g., documents/report.txt (if you’re in /home/john).
  • Environment Variables: Dynamic values that affect shell behavior (e.g., $PATH lists directories for executable commands, $HOME is your user directory).

Essential Shortcuts

  • Tab Completion: Press Tab to auto-complete commands, filenames, or directories (e.g., type cd doc + Tab to complete documents).
  • Command History: Press Up/Down Arrow to cycle through past commands, or use history to list all:
    history  # Shows recent commands with line numbers
    !5       # Re-run the 5th command in history
  • Search History: Press Ctrl + R, type a keyword, and press Enter to run a matching command.
  • Cancel Command: Press Ctrl + C to stop a running command.

Essential Commands

Master these commands to navigate and manage your system efficiently.

1. Navigation Commands

pwd (Print Working Directory)

Shows your current directory.

john@ubuntu:~$ pwd
/home/john  # Output: Your current path

cd (Change Directory)

Navigate to a directory.

cd documents          # Move to "documents" (relative path)
cd /home/john/music   # Move to "music" (absolute path)
cd ..                 # Move up one directory (parent folder)
cd ~                  # Move to your home directory (shortcut: cd)
cd -                  # Move to the previous directory

ls (List Directory Contents)

List files and directories in the current folder.

ls                    # Basic list
ls -l                 # Long format (permissions, size, date)
ls -la                # Show all files (including hidden, starting with .)
ls -lh                # Long format with human-readable sizes (e.g., 2K, 5M)
ls /home/john         # List contents of a specific directory

Example output of ls -l:

-rw-r--r-- 1 john john  1024 Jan 1 12:00 report.txt
drwxr-xr-x 2 john john  4096 Jan 1 10:00 documents/
  • d indicates a directory; - indicates a file.
  • rw-r--r-- are file permissions (read/write/execute for user/group/others).

2. File/Directory Management

mkdir (Make Directory)

Create a new directory.

mkdir projects               # Create "projects"
mkdir -p work/reports        # Create nested directories (-p = parent)

touch (Create Empty File)

Create a blank file or update a file’s timestamp.

touch notes.txt              # Create "notes.txt"

cp (Copy Files/Directories)

Copy files or directories.

cp notes.txt backup/         # Copy "notes.txt" to "backup" directory
cp -r projects/ archives/    # Copy directory (-r = recursive)

mv (Move/Rename)

Move files/directories or rename them.

mv report.txt documents/     # Move "report.txt" to "documents"
mv oldname.txt newname.txt   # Rename "oldname.txt" to "newname.txt"

rm (Remove Files/Directories)

Delete files or directories (use with caution!).

rm notes.txt                 # Delete "notes.txt"
rm -i report.txt             # Prompt before deletion (-i = interactive)
rm -r old-projects/          # Delete directory and contents (-r = recursive)
# WARNING: rm -rf / deletes EVERYTHING (never run as root!)

nano/vi (Text Editors)

Edit files directly in the terminal.

nano todo.txt   # Open "todo.txt" in Nano (user-friendly editor)
vi report.txt   # Open "todo.txt" in Vim (powerful, steeper learning curve)

3. Viewing Files

cat (Concatenate)

Display file contents.

cat todo.txt    # Print entire file
cat file1.txt file2.txt > combined.txt  # Merge files into "combined.txt"

less (View Large Files)

Browse files interactively (scroll with Up/Down arrows, exit with q).

less large-log-file.txt

head/tail (View Start/End of Files)

head -5 report.txt   # Show first 5 lines
tail -10 log.txt     # Show last 10 lines
tail -f /var/log/syslog  # "Follow" a log file (updates in real-time)

4. System Information

whoami

Show your current username.

john@ubuntu:~$ whoami
john

uname (Unix Name)

Show system kernel info.

uname -a  # Show all details (kernel version, hostname, architecture)

df/free (Disk/Memory Usage)

df -h     # Disk space (-h = human-readable: GB, MB)
free -h   # Memory usage

top/htop (Process Monitor)

View running processes and resource usage.

top       # Basic process monitor (exit with q)
htop      # Enhanced version (install with sudo apt install htop on Debian/Ubuntu)

5. User & Privileges

sudo (Superuser Do)

Execute commands as the root (administrator) user (required for system changes).

sudo apt update   # Update package list (Debian/Ubuntu)
sudo systemctl restart apache2  # Restart a service

su (Switch User)

Switch to another user (e.g., root).

su - root   # Switch to root (enter root password)
su john     # Switch to user "john"

6. Package Management

Install/remove software (distro-specific):

Debian/Ubuntu (APT)

sudo apt update          # Update package list
sudo apt install git     # Install "git"
sudo apt remove git      # Remove "git"
sudo apt upgrade         # Upgrade all installed packages

Fedora/RHEL (DNF)

sudo dnf check-update    # Check for updates
sudo dnf install git     # Install "git"
sudo dnf remove git      # Remove "git"

Advanced Usage: Pipes, Redirection, and Scripting

Pipes (|)

Chain commands to process output sequentially. Use | to send the output of one command to another.

Example: List all .txt files and count them:

ls -l | grep .txt | wc -l  # ls → filter for .txt → count lines
  • ls -l: List files in long format.
  • grep .txt: Keep only lines containing .txt.
  • wc -l: Count the number of lines (files).

Redirection

Redirect command output to files or input from files.

  • Overwrite a file: >

    echo "Hello World" > greeting.txt  # Write "Hello World" to greeting.txt (overwrites existing content)
  • Append to a file: >>

    echo "Goodbye" >> greeting.txt  # Add "Goodbye" to the end of greeting.txt
  • Input from a file: <

    sort < unsorted.txt > sorted.txt  # Sort "unsorted.txt" and save to "sorted.txt"

Wildcards

Match files/directories using patterns:

  • *: Any sequence of characters (e.g., *.txt matches all .txt files).
  • ?: Any single character (e.g., file?.txt matches file1.txt, fileA.txt).
  • []: Any character in brackets (e.g., file[1-3].txt matches file1.txt, file2.txt, file3.txt).

Example: Delete all .log files:

rm *.log

Shell Scripting

Automate tasks with shell scripts (.sh files). Here’s a simple example:

  1. Create a script named backup.sh:
nano backup.sh
  1. Add this content (shebang #!/bin/bash tells the system to use Bash):
#!/bin/bash
# Backup documents to /tmp/backup
SOURCE="/home/john/documents"
DEST="/tmp/backup_$(date +%Y%m%d).tar.gz"  # Include date in filename

tar -czf "$DEST" "$SOURCE"  # Compress SOURCE into DEST
echo "Backup saved to $DEST"
  1. Make it executable and run:
chmod +x backup.sh  # Grant execute permission
./backup.sh         # Run the script

Common Practices

  • Use sudo Sparingly: Only use sudo for commands that require admin privileges to avoid accidental system changes.
  • Navigate Efficiently: Use cd ~ to return home, cd - to toggle directories, and tab completion to save time.
  • Organize Files: Store related files in directories (e.g., projects/, downloads/) to avoid clutter.
  • Check History: Use history | grep "command" to find past commands (e.g., history | grep apt to see package commands).

Best Practices for Safety and Efficiency

  1. Avoid rm -rf as Root: Deleting with rm -rf is irreversible. Test with ls first (e.g., ls old-files/ before rm -r old-files/).
  2. Use Absolute Paths for Critical Tasks: When running scripts or deleting files, use absolute paths (e.g., /home/john/file.txt) to avoid mistakes.
  3. Comment Scripts: Add comments (#) to explain script logic for future you or collaborators.
  4. Keep Systems Updated: Regularly run sudo apt upgrade (Debian/Ubuntu) or sudo dnf upgrade (Fedora) to patch security vulnerabilities.
  5. Backup Data: Use rsync or tar to back up important files to external drives or cloud storage.
  6. Secure Sensitive Data: Restrict file permissions with chmod (e.g., chmod 600 secret.txt to allow only your user to read/write).

Troubleshooting Common Issues

”Command Not Found”

  • The command isn’t installed: Use your package manager to install it (e.g., sudo apt install git).
  • The command isn’t in $PATH: Add its directory to $PATH (e.g., export PATH=$PATH:/new/directory).

”Permission Denied”

  • You lack access: Use sudo (e.g., sudo cp file.txt /root/).
  • File permissions are restrictive: Adjust with chmod (e.g., chmod +r file.txt to allow reading).

”Disk Full”

  • Check disk usage: df -h.
  • Delete large/unneeded files: Use du -sh * to find large directories, then delete with rm.

Conclusion

The Linux command line is a powerful tool that rewards practice. Start with essential commands like ls, cd, and cp, then gradually explore advanced features like pipes, scripting, and automation. By following best practices—such as avoiding risky commands and organizing your workflow—you’ll become proficient in managing Linux systems efficiently and safely.

Remember: The CLI is about problem-solving. Use man command (e.g., man ls) to read documentation, and don’t fear experimenting in a non-critical environment (like a virtual machine).

References