How to Use Command Line on Linux

Written by

Reviewed by

Last updated: July 6, 2024

Expert verified

SVG Image

TL;DR

To learn how to use the command line on Linux, you can start with these methods:

  1. Open a Terminal: Use keyboard shortcuts or search the application menu.
  2. Basic Navigation: Use pwd, ls, and cd to move around directories.
  3. Creating Files and Folders: Use mkdir for folders and touch for files.
  4. Managing Files: Copy, move, and delete files with cp, mv, and rm.
  5. File Permissions: Change permissions with chmod and ownership with chown.
  6. Superuser Access: Use sudo for administrative tasks and su to switch users.
  7. Hidden Files: View and manage hidden files with ls -a.
  8. Command Line Utilities: Use text editors, system monitoring, and network tools.
  9. Customize the CLI: Set environment variables, create aliases, and adjust the prompt.

Using the command line in Linux might seem overwhelming at first, but don’t worry—I’ve got you covered. In this guide, I’ll walk you through everything you need to know, from basic navigation and file management to using superuser privileges. You’ll also get tips on troubleshooting common errors. By the end, you’ll feel more confident and ready to tackle your Linux system like a pro. Let’s unlock the power of the command line together!

What is the Command Line Interface (CLI)?

The Command Line Interface (CLI) is a text-based way to interact with your computer. Instead of using a mouse to click on icons and menus, you type commands to perform tasks. In Linux, the CLI allows you to control almost every aspect of the operating system.

Importance of Learning CLI for Linux Users

Learning the CLI is crucial for Linux users because it provides powerful tools for managing the system. While graphical interfaces are user-friendly, the CLI offers deeper access and control, which is essential for advanced tasks and troubleshooting.

Benefits of Using the Command Line on Linux

  • Speed and Efficiency: The CLI is faster for many tasks. Instead of navigating through multiple menus, you can type a single command to accomplish a task. This efficiency is especially useful for repetitive tasks.
  • Greater Control and Flexibility: The CLI provides greater control over the system. You can execute complex commands and scripts that are not possible with graphical interfaces. This flexibility allows you to customize the system to your needs.
  • Automation of Tasks: The CLI allows you to automate tasks by writing scripts. You can schedule these scripts to run at specific times, reducing the need for manual intervention and increasing productivity.

How to Open a Terminal

Opening a terminal is the first step to using the command line in Linux. Here are two common methods explained with a clear purpose and step-by-step guide:

1. Using Keyboard Shortcuts

Keyboard shortcuts provide a quick and efficient way to open the terminal without navigating through menus.

  1. Press Ctrl+Alt+T. This shortcut is commonly available on many Linux distributions.
opening command line on linux using keys
  1. If Ctrl+Alt+T doesn’t work, you can set up a custom shortcut:
  2. Open your system settings or preferences menu.
opening system settings
  1. Navigate to the Keyboard section.
navigating to keyboard section
  1. Look for the Shortcuts or Keybindings tab.
find keyboard shortcut or keybinding option
  1. Add a new shortcut for the terminal application and assign it your preferred key combination.
setting shortcut key to open terminal 1

2. Searching Through Application Menus

If you prefer using graphical menus, you can open the terminal by searching through the application menus.

  1. Click on the application menu button (often at the bottom left or top left of the screen).
opening application menu
  1. In the search bar, type Terminal. Look for the terminal application in the search results. Click on the terminal application to open it.
launching terminal from application menu

    Understanding the Terminal Window

    Once you have the terminal open, understanding its layout is essential for efficient use. Here’s a brief overview of its main components:

    • Shell Prompt: Indicates that the terminal is ready for a command. It usually includes your username, hostname, and current directory, followed by a $ sign (for regular users) or # (for the root user).
    • Command Input Area: The line where you type your commands. After typing a command, press Enter to execute it.
    • Command Output Area: Displays the results of your commands and any messages from the system.

    Basic Command Line Navigation

    Navigating the command line is essential for using Linux effectively. Here’s a simple guide to help you understand the file system hierarchy, basic navigation commands, and using wildcards and patterns.

    Understanding the File System Hierarchy

    The Linux file system is organized in a hierarchical structure. Here’s a quick overview:

    • Root Directory (/): The top-level directory. Everything in the system starts from here.

    Common Directories:

    • /home: Contains user home directories. Each user has a separate directory here.
    • /etc: Stores system configuration files.
    • /var: Holds variable data like logs.
    • /usr: Contains user programs and data.

    1. Basic Navigation Commands

    To navigate through the Linux file system, you’ll use a few basic commands. Here’s how to use them:

    1. pwd (Print Working Directory): 

    This command shows your current directory.

    Type the following command and press Enter:

    pwd
    showing current directory
    1. ls (List Directory Contents): 

    This command lists the files and directories in your current location.

    Enter the following command:

    ls
    viewing contents of a current directory
    1. cd (Change Directory): 

    This command changes your current directory.

    1. Type cd followed by the path to the directory you want to navigate to.
    cd /home/user/Documents 
    changing directory

    It will changes to the Documents directory.

    1. To go back to the previous directory, type:
    cd -
    navigating to previous directory
    1. To go to your home directory, type:
    cd ~
    navigating to home directory 1

    2. Using Wildcards and Patterns

    Wildcards and patterns help you work with multiple files or directories that match a specific criteria. Here’s how to use them:

    1. * (asterisk):  Matches any number of characters.
    ls *.txt
    listing all files of same pattern using asterisk
    1. ? (question mark): Matches a single character.
    ls file?.txt 
    listing all files that matches single character
    1. [ ] (square brackets): Matches any character within the brackets.
    ls file[12].txt
    listing files that matches pattern in brackets

    Creating Folders and Files

    Creating and managing files and directories is a fundamental skill in using the Linux command line. This guide will help you understand how to create directories, create files, use redirection operators, and view file contents.

    1. Creating Directories

    To create new folders (directories) for organizing your files.

    Access your command window. Type mkdir followed by the name of the directory you want to create.

    mkdir new_folder

    Press Enter.

    The terminal creates a new directory named new_folder in your current location.

    creating new directory

    2. Creating Files

    To create new files, either empty or with initial content.

    Type touch followed by the name of the file you want to create.

    touch new_file.txt

    Press Enter.

    The terminal creates an empty file named new_file.txt in your current location.

    creating new file in current location

    3. Using Redirection Operators:

    • >: Creates a new file or overwrites an existing file with specified content.

    Type a command followed by > and the name of the file.

    echo "Hello World" > file.txt

    The terminal creates file.txt with the content Hello World or overwrites it if it already exists.

    creating or overwriting file with specified content
    • >>: Appends content to an existing file without overwriting it.

    Type a command followed by >> and the name of the file.

    echo "More text" >> file.txt

    The terminal appends More text to file.txt.

    appending content to a file without overwriting it

    4. Viewing File Contents

    To read and display the contents of files in different ways.

    • Using cat

    Concatenate and display file content.

    Type cat followed by the name of the file.

    cat file.txt

    The terminal displays the entire content of file.txt.

    viewing content of a file in terminal
    • Using less or more

    View file content one page at a time.

    Type less or more followed by the name of the file.

    less file.txt
    
    more file.txt

    Use the arrow keys to navigate through the file.

    viewing content of a file one page at a time
    • Using head:

    View the first 10 lines of a file.

    Type head followed by the name of the file.

    head file.txt

    The terminal displays the first 10 lines of file.txt.

    viewing first 10 lines of a file
    • Using tail:

    View the last 10 lines of a file.

    Type tail followed by the name of the file.

    tail file.txt

    The terminal displays the last 10 lines of file.txt.

    viewing last 10 lines of a file

    Managing Files and Directories

    Managing files and directories is a key part of using the Linux command line. This guide will help you understand how to copy, move, rename, delete, archive, and compress files and directories.

    1. Copying Files and Directories

    To create a duplicate of a file or directory.

    1. Open the terminal.
    2. Type cp followed by the source file or directory and the destination.
    cp file.txt /home/user/Documents

    Press Enter.

    The terminal copies file.txt to the specified destination directory.

    copying file to specified destination

    2. Moving and Renaming Files and Directories

    To move files or directories to a new location or to rename them.

    Type mv followed by the source file or directory and the destination. Run the following command to move: 

    mv file.txt /home/user/Documents

    Execute the following command to rename the file: 

    mv file.txt new_name.txt
    renaming a file using mv command

    3. Deleting Files and Directories

    To remove files or directories from the system.

    • Removing Files:

    Type rm followed by the file name.

    rm file.txt

    The terminal removes file.txt.

    deleting a file in linux
    • Removing Empty Directories:

    Type rmdir followed by the directory name.

    rmdir empty_folder

    The terminal removes the empty directory empty_folder.

    deleting an empty directory in linux
    • Removing Directories and Their Contents:

    Type rm -r followed by the directory name.

    rm -r full_folder

    The terminal removes full_folder and all its contents recursively.

    deleting a directory with its content in linux

    4. Archiving Files and Extracting Files

    To bundle multiple files into a single archive.

    • Creating an Archive:

    Open the terminal.

    Type tar -cvf followed by the name of the archive file and the directory to be archived.

    tar -cvf archive.tar directory/

    The terminal creates archive.tar containing the contents of directory/.

    creating an archive of a directory
    • Extracting an Archive:

    Type tar -xvf followed by the name of the archive file.

    tar -xvf archive.tar

    The terminal extracts the contents of archive.tar into the current directory.

    extracting an archive in linux

    5. Compressing and Decompressing Files

    Compressing files to save space.

    • Compressing a File:

    Launch the terminal.

    Type gzip followed by the name of the file to compress.

    gzip file.txt

    The terminal compresses file.txt to file.txt.gz.

    compressing a file in linux
    • Decompressing a File:

    Type gunzip followed by the name of the compressed file.

    gunzip file.txt.gz

    The terminal decompresses file.txt.gz back to file.txt.

    uncompressing a file in linux

    Understanding File Permissions

    File permissions in Linux control who can read, write, or execute a file. Understanding and managing these permissions is crucial for system security and proper file management. This guide will help you grasp the basics of file permissions, how to change them, and how to manage file ownership.

    File Permission Basics

    To control access to files and directories, ensuring that only authorized users can view, modify, or execute them.

    Ownership:

    • User (u): The owner of the file.
    • Group (g): A group of users who have access to the file.
    • Others (o): All other users who have access to the file.

    Permissions:

    • Read (r): Allows viewing the content of the file.
    • Write (w): Allows modifying the content of the file.
    • Execute (x): Allows running the file as a program.

    1. Viewing File Permissions

    Open the terminal.

    Type ls -l followed by the name of the directory containing the file(s).

    ls -l /home/user

    Press Enter.

    The terminal displays a detailed list of files, including their permissions.

    viewing permissions of files in a directory
    • -rwxr-xr– indicates the permissions.
    • rwx: User can read, write, and execute.
    • r-x: Group can read and execute.
    • r–: Others can read only.

    2. Changing Permissions

    To modify who can read, write, or execute a file.

    • Symbolic Mode:

    To add, remove, or set specific permissions using symbols.

    Type chmod followed by the desired permissions and the file name.

    Use the format chmod [who][operator][permission] file_name.

    chmod u+r file.txt

    The terminal updates the permissions for file.txt.

    changing permission of file through symbols
    • Numeric Mode:

    To set permissions using a three-digit octal number where each digit represents user, group, and others respectively.

    Use the format chmod [mode] file_name.

    chmod 755 file.txt
    • 7 (rwx): User can read, write, and execute.
    • 5 (r-x): Group can read and execute.
    • 5 (r-x): Others can read and execute.

    The terminal updates the permissions for file.txt.

    changing permission of file using numeric values

    3. Changing Ownership

    To change the user and/or group that owns a file or directory.

    Type chown followed by the new owner and the file name.

    • Changing User and Group:
    sudo chown user:group file.txt
    changing ownership and group of a file
    • Changing Only Group:
    sudo chgrp group file.txt

    The terminal updates the ownership of file.txt.

    changing only group of a file

    Understanding the Superuser (root)

    The superuser has unrestricted access to all commands and files on the system. This account is used for administrative tasks and system maintenance. However, using the superuser account comes with risks; improper use can lead to system damage. Always exercise caution when operating as the superuser.

    1. Using sudo for Superuser Access

    To execute a command with superuser privileges without logging in as the root user. This method is safer and more secure for performing administrative tasks.

    1. Access your command window.
    2. Type sudo followed by the command you want to execute with superuser privileges.
    sudo apt update

    The terminal prompts you to enter your user password.

    running a command with super user privileges
    1. Type your password and press Enter.

    The command runs with superuser privileges.

    entering password for super user authorization

    2. Configuring sudoers File:

    To manage which users can use sudo and what commands they can run.

    1. Execute the following command.
    sudo visudo 

    The visudo editor opens the sudoers file.

    opening sudoers file
    1. Enter your password if prompted.
    1. Add or modify user permissions as needed. For example, to grant all permissions to a user named “username”, add: 
    username ALL=(ALL) ALL
    1. Save and close the file (usually by pressing Ctrl+X, then Y, and Enter in nano).
    granting all permissions to a user

    3. Switching to the Root User

    To temporarily switch to the root user account or another user account to perform administrative tasks that require full superuser access.

    • Switch to Root:
    1. Run the following command:
    su -

    The terminal prompts you to enter the root password.

    switching to root user 2
    1. Type the root password and press Enter.

    Your command prompt changes to indicate that you are now the root user.

    enter password to login as root user 1
    • Switch to Another User:
    1. Enter su followed by the username of the account you want to switch to.
    su username
    1. Type the user’s password and press Enter.

    Your command prompt changes to indicate that you are now operating as the specified user.

    switching to another user account

    Working with Hidden Files

    Hidden files in Linux are used to store configuration settings and other critical data that should not be modified frequently. These files and directories start with a dot (.) to make them invisible in regular directory listings.

    1. Listing Hidden Files

    To view hidden files and directories that are not shown by default.

    Open the command prompt.

    Type the following command and press Enter.

    ls -a

    The terminal displays all files and directories, including hidden ones.

    listing all files including hidden files

    2. Creating and Managing Hidden Files

    To create and modify hidden files and directories for storing configuration settings or other sensitive data.

    • Creating Hidden Files:

    Type touch followed by the name of the hidden file you want to create (starting with a dot).

    touch .hiddenfile

    The terminal creates an empty hidden file named .hiddenfile.

    creating a hidden file
    • Creating Hidden Directories:

    Type mkdir followed by the name of the hidden directory you want to create (starting with a dot).

    mkdir .hiddendir

    The terminal creates a hidden directory named .hiddendir.

    creating a hidden directory
    • Editing Hidden Files:

    Type a text editor command (e.g., nano, vim) followed by the name of the hidden file you want to edit.

    nano .hiddenfile

    The text editor opens the hidden file, allowing you to make changes.

    opening hidden file in nano editor

    After editing, save and close the file. For nano, press Ctrl+X, then Y, and Enter.

    editing hidden file in nano editor

    Using Command Line Utilities

    Command line utilities in Linux help you perform various tasks efficiently. This guide will introduce you to some essential utilities for text editing, system monitoring, and network management.

    1. Text Editors

    Text editors allow you to create and edit text files directly from the command line.

    • Nano:

    Nano is easy to use, making it great for beginners.

    1. Open the terminal.
    2. Type nano followed by the file name you want to edit.
    nano file.txt
    opening a file in nano text editor 1

    Press Enter. Nano opens the file, and you can start editing.

    editing file in nano editor
    • Vim:

    Vim has many advanced features but takes time to learn.

    Type vim followed by the file name you want to edit.

    vim file.txt

    Vim opens the file in command mode. 

    opening a file in vim text editor

    Press i to switch to insert mode and start editing.

    editing file in vim editor
    • Emacs:

    Emacs can be customized extensively and supports many features.

    Enter emacs followed by the file name you want to edit.

    emacs file.txt
    opening a file in emacs editor 1

    Emacs opens the file, and you can start editing.

    editing file in emacs editor

    2. System Monitoring Tools

    These tools help you monitor the system’s performance and resource usage.

    • top:

    Shows a list of running processes and their resource usage.

    1. Access your Terminal window.
    2. Run the following command and press Enter.
    top
    monitoring system performance using top command

    The ouput will look like this:

    top command output
    • htop:

    Provides a more user-friendly and interactive interface.

    Execute the following command:

    htop
    monitoring system performance using htop command

    The interface will look like this:

    htop command output
    • df:

    Displays the amount of disk space used and available on filesystems.

    Type the following command and press Enter.

    df
    viewing used disk space
    • du:

    Shows the disk usage of directories and their contents.

    Type du followed by the directory path.

    du /home/user
    viewing disk usage of directories and their content

    3. Network Utilities

    These utilities help you manage and troubleshoot network connections.

    • ping:

    Checks if a remote host is reachable.

    Enter the Terminal window.

    Type ping followed by the hostname or IP address.

    ping google.com
    checking if the remote host is reachable
    • ifconfig:

    Displays and configures network interface settings.

    Execute the following command:

    ifconfig
    viewing network interface settings
    • netstat:

    Shows network connections, routing tables, interface statistics, and more.

    Run the following command:

    netstat
    viewing network statistics using netstat

    Customizing the Command Line Environment

    Customizing your command line environment makes your work more efficient and tailored to your needs. This guide will help you understand how to set environment variables, customize the shell prompt, and create aliases and functions.

    1. Environment Variables

    Environment variables store information that can affect the behavior of running processes. Common variables include paths to executable files, the current user’s home directory, and more.

    • Setting Variables:

    Open the terminal.

    Set a variable by typing export followed by the variable name and value.

    export PATH=$PATH:/new/path

    The variable is now set for the current session.

    setting new variable path

    Common Variables:

    • PATH: Directories where the shell looks for executable files.
    • HOME: The current user’s home directory.
    • USER: The current logged-in username.

    2. Customizing the Shell Prompt

    Customizing the shell prompt can provide useful information and improve your workflow by displaying the current user, host, and directory.

    1. Customize the prompt by typing export PS1= followed by the desired prompt format.
    export PS1="\u@\h:\w$ "
    • \u: Username
    • \h: Hostname
    • \w: Current working directory
    1. Press Enter. Your shell prompt now displays the custom format.
    changing shell prompt format

    3. Creating Functions

    Functions save time by allowing you to create shortcuts for frequently used commands or to group multiple commands into one.

    1. Open the terminal.
    2. Create a function by typing the function name followed by () and {} containing the commands.
    myfunction() { echo "Hello, $1"; }

    This function prints Hello followed by the first argument you provide.

    The function is now defined for the current session.

    creating a function to call it
    1. Call the function by typing its name followed by an argument.
    myfunction World
    1. Press Enter. The terminal displays Hello, World.
    calling a function

    Common Issues When Using the Command Line on Linux

    Using the command line on Linux can be powerful but sometimes challenging, especially for beginners. Here are five common issues you might encounter while using the CLI and how to handle them effectively.

    • ⚠️ Permission Denied: You try to run a command, but the terminal says “Permission denied.” This happens because you don’t have the necessary permissions. Try using sudo before the command or check file permissions with ls -l.
    • 🔍 Command Not Found: You enter a command, but the terminal responds with “Command not found.” This means the command isn’t installed or isn’t in your PATH. Ensure the program is installed and check the PATH variable.
    • No Such File or Directory: You specify a file or directory, but the terminal can’t find it. This usually means there’s a typo in the path or the file/directory doesn’t exist. Double-check the path and ensure the file/directory exists.
    • 📝 File Locked: You attempt to edit a file, but it’s locked or in use by another process. This can prevent changes and lead to frustration. Use lsof to find the process using the file and consider stopping the process or waiting until it’s free.
    • 💾 Disk Space Full: You try to save or create files, but you get an error about insufficient disk space. Use df -h to check available disk space. Free up space by deleting unnecessary files or moving them to another storage.

    Wrapping Up

    In conclusion, this step-by-step guide has shown you how to effectively use the command line on Linux, from opening a terminal and navigating the file system to managing permissions and using superuser privileges. By understanding these basics, you can perform tasks more efficiently and troubleshoot common errors with confidence.

    If you’re eager to expand your knowledge further, I recommend exploring:

    • Explore using the help command in Linux to access detailed command information, enhancing your knowledge and problem-solving skills.
    • Discover methods to check system logs in Linux, which will assist you in monitoring system activities and troubleshooting effectively.
    • Learn how to identify the shell you’re using, helping you optimize your environment and improve your workflow.

    Frequently Asked Questions

    How do I create a new user from the command line?

    To create a new user from the command line, use the sudo useradd username command, replacing username with your desired username. After that, set a password using sudo passwd username. This adds the user to the system and allows them to log in with the password you set.

    What are the differences between bash and sh?

    bash (Bourne Again Shell) is an enhanced version of sh (Bourne Shell). It includes features like command history, tab completion, and scripting improvements. While sh is more basic and traditionally used for scripts, bash offers a more user-friendly and powerful environment for both scripting and interactive use.

    What is the purpose of the man command?

    The man command displays the manual pages for other commands, providing detailed information on usage, options, and examples. By typing man followed by a command name, you can access comprehensive documentation. This is essential for understanding command functionalities and options in Linux, serving as a valuable resource for users.

    How can I change the default shell for my user account?

    To change the default shell for your user account, use the chsh -s /bin/shellname command, replacing shellname with your desired shell, such as bash or zsh. This updates your shell setting, and changes take effect the next time you log in. Ensure the shell is installed before changing.

    Ojash

    Author

    Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

    Akshat

    Reviewer

    Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

    Share this article
    Shareable URL
    Prev Post

    What is Debian? One of the Oldest Linux Distributions

    Next Post

    50 Linux Commands You MUST Know

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Read next