How To Use The Linux Command Line

by DD

April 22, 2025

Introduction

Linux is an open-source operating system based on Unix, originally developed in the early 1990s. It is widely used for servers, personal computers, and embedded systems due to its stability, security, and flexibility. GNU/Linux refers to Linux distributions that include GNU utilities, forming a complete operating system.

A shell is a command-line interpreter that enables users to interact with the operating system. It processes commands entered by the user, executing them and returning results. Popular Linux shells include Bash, Zsh, and Fish. Bash being the most common. This information in this tutorial should be applicable to all Unix-like shells.

The command line is a textual interface that allows users to interact with the operating system by entering commands. When a user types a command and presses Enter, the shell interprets the input, executes the corresponding operation, and typically returns output to the terminal. This output could be confirmation of a successful action, an error message, or data generated by the command.

A command is an instruction given to the operating system via the shell. Commands can have options (or flags), which modify their behavior, and arguments, which specify the data they act upon. Many commands include a --help or -h flag, providing brief usage information to guide users.

A terminal emulator is a program that provides access to the shell, allowing users to execute commands from a graphical environment. Examples include GNOME Terminal, Konsole (KDE), and MATE Terminal.

Opening the Terminal

How the terminal is opened depends on the desktop environment you are using:

If your desktop environment or system isn’t listed here, refer to the official documentation for your Linux distribution or desktop environment to find instructions on launching the terminal. You can also search online or check community forums for guidance specific to your setup.

Navigation

When you open a terminal, you'll see a blinking cursor next to a prompt. This prompt usually looks something like:

user@hostname:~$

The $ symbol indicates that the terminal is ready to accept a command. To interact with the system, you type a command at this prompt and press Enter to execute it.

Let’s try running our first command. Type:

pwd

into the terminal and then press Enter. After pressing Enter, the terminal will respond with output similar to

/home/user

The pwd command stands for print working directory—it tells you your current location within the system’s filesystem. The output /home/user is a directory path, representing where you are right now.

In Linux, files are organized into a hierarchical directory structure, starting with the root directory, represented by /. Every other directory is contained within /, forming a tree-like structure. A directory path shows the location of a directory within this system.

For example, consider the path /home/user:

Each forward slash (/) in a path separates directories, showing how they are nested within one another.

Your working directory is the directory you are currently interacting with. When you open a terminal, it usually starts in your home directory (/home/username), a personal space where users store files.

If you ever encounter a new command and want to learn how to use it, you can often append --help to the command. This is an option, a special flag that modifies the behavior of a command. Many Linux commands support this option and will return a brief help message explaining their usage. For example, try running:

pwd --help

When you run a command with the --help option, it usually displays a short description of the command, a list of available options, and sometimes other useful information.

This will display information about the pwd command and its available options. Using --help is a quick way to familiarize yourself with a command’s functionality without needing to search online or consult manuals.

Help messages follow a similar format across many Linux commands, making them a reliable way to explore new tools and their functions.

The next command we are going to learn is ls. Type the following at the terminal prompt and press Enter:

ls

You should see a list of names displayed on the screen, like this:

Desktop  Documents  Downloads  Music  Pictures  Videos

This output represents the contents of your current working directory.

In a Linux system, everything is organized into either files or directories:

In the output of ls, some names may represent directories, while others may be files. If you just opened a terminal, your working directory is likely your home directory, where personal files and folders are stored.

By default, ls only displays names, so it’s not immediately obvious which are files and which are directories. However, there are ways to tell them apart. Try running ls with the -F option. This adds a / at the end of directory names, making them easy to spot.

ls -F

Returns something like:

Desktop/  Documents/  Downloads/  Notes.txt  Picture.jpg  Videos/

Here, Desktop/, Documents/, and Videos/ are directories, while Notes.txt and Picture.jpg are files.

The exact files and directories displayed on your system may differ from our examples. Your home directory might contain different folders or fewer files, depending on your setup. Don’t worry if things look a little different—the important part is understanding how to list and interpret directory contents.

You can also specify a different directory by providing its path as an argument. Try running:

ls /etc

This command tells ls to list the contents of /etc, a system directory that contains configuration files. You can replace /etc with any directory path to inspect different locations on your system.

Two special characters, . and .., help navigate directories:

You can use them with ls to view files in related directories. Try:

ls ./Documents

This lists the contents of the Documents folder inside the current directory.

ls ..

This lists the contents of the parent directory, helping you look one level up.

Paths can be absolute or relative:

Absolute paths start from the root directory (/) and describe a full location. Example:

ls /var/log

This lists the contents of /var/log, regardless of your current location.

Relative paths start from the current directory and describe a location based on where you are. Example:

ls ./Downloads

This lists files in the Downloads folder in your current working directory.

The ~ character is a shortcut for your home directory, allowing easy access to personal files. Instead of typing the full path to your home directory (/home/username), you can simply use ~:

ls ~

This lists everything in your home directory, no matter where you are in the filesystem.

Similarly, you can navigate directly to a folder inside your home directory:

ls ~/Documents

Now that you know how to list files and directories, let's learn how to move between directories using the cd command.

Let’s change into the Documents directory inside your home folder. Type the following and press Enter:

cd ~/Documents

Nothing may appear to happen, but let’s confirm that our location has changed. Run:

pwd

If the command was successful, you’ll see something like:

/home/user/Documents

This confirms that your current working directory is now Documents.

Now, list the contents of this directory to see what’s inside:

ls

This displays files and folders within Documents, just like ls did in your home directory.

If you want to return to the parent directory (the directory above your current one):

cd ..

or, you can move back to your home directory by running:

cd ~

And just like before, you can check where you are with pwd and list contents with ls.

Every Linux system can have multiple users, each with their own home directory. A user’s home directory is a personal workspace where they store files, configuration settings, and personal directories. When you open a terminal, you typically start in your home directory, but other users on the system have their own separate spaces.

For example, consider these home directories:

/home/alice
/home/bob

Each user has their own /home/username directory, ensuring that their files remain separate from others on the system.

Not all files and directories are accessible to every user. Linux uses a permission system to control who can read, modify, or execute files. Some files belong to specific users and groups, restricting others from accessing them.

For example:

Linux has a special superuser known as root, which has unrestricted access to the entire system. The root user can modify any file, install software, and change system configurations. Regular users typically do not operate as root to avoid accidental system-wide changes.

To see which user you are currently logged in as, you can use the whoami command:

whoami

This will return your username, helping you confirm which account you’re operating under. If you’re logged in as root, it will display root, indicating that you have administrative privileges. You are most likely not currently operating as root.

Creating Our Own Directories and Files

Now that we know how to navigate the filesystem, let’s start making our own directories and files.

The mkdir command allows us to create a new directory. Try running:

mkdir my_directory

This creates a new directory named my_directory inside your current working directory.

To confirm that it was created, list the contents of the current directory:

ls

You should see my_directory listed among the other files and folders.

Now run:

cd my_directory

to enter our new directory. Again, you can run pwd and ls to check where we are and list the contents of this new directory (It should be empty).

The echo command simply prints text to the terminal. Try:

echo "Hello, world!"

Output:

Hello, world!

When a command produces output, it typically prints it to the terminal. This is called standard output (stdout). However, we can redirect this output to a file instead of displaying it on screen.

We can use > to save the output of a command to a file:

echo "Hello, world!" > my_file.txt

Now, instead of printing to the terminal, the text "Hello, world!" is saved inside my_file.txt. To check:

cat my_file.txt

This cat command displays the contents of my_file.txt, showing:

Hello, world!

Using >> instead of > appends text to an existing file instead of overwriting it:

echo "This is a second line." >> my_file.txt

Now, my_file.txt contains both lines You can confirm this by running cat my_file.txt again.

The mv command lets you move or rename a file:

mv my_file.txt renamed_file.txt

This renames my_file.txt to renamed_file.txt.

mv renamed_file.txt ../ 

This moves the file to inside the current parent directory. You can confirm this with ls ...

To make a duplicate of a file, use cp:

cp ../renamed_file.txt copy_of_file.txt

This creates a new file called copy_of_file.txt with the same contents as renamed_file.txt. Once again, you can use the cat command to check that the contents of these two files are the same.

To delete a file:

rm copy_of_file.txt

Let's return back to our home directory by running cd ~.

To delete a directory and its contents:

rm -r my_directory

Be careful with rm, as deleted files cannot be recovered easily.

Package Management

Linux software is typically installed and managed using package managers, tools that handle downloading, updating, and removing applications from repositories. Different Linux distributions use different package managers, but the core functionality remains the same.

Let’s use nano, a simple text editor, as an example. Some Linux installations include nano by default, while others may require manual installation.

To check if nano is already installed, use:

which nano

If installed, this command will return the path to nano, something like:

/usr/bin/nano

If nothing appears, it means nano is likely not installed, and you’ll need to install it using your package manager.

Most package management commands require administrative privileges because they modify system files. The sudo command allows regular users to temporarily execute commands as the root user, who has unrestricted access to the system. sudo is short for super-user do.

Arch-based distributions like Manjaro and Arch Linux use pacman to manage packages.

Before we install anything, it's a good idea to make sure our system is up-to-date. Run:

sudo pacman -Syu

to update your operating system.

To install nano, run:

sudo pacman -S nano

Here’s what happens:

On Debian-based distributions like Ubuntu, apt-get is used instead. To update, run:

sudo apt-get update && sudo apt-get upgrade

The && symbol here separates two different commands. As soon as the first is finished, sudo apt-get update, the second, sudo apt-get upgrade, will be ran.

To install nano, now run:

sudo apt-get install nano

The concept is the same— apt-get install fetches and installs the package.

Different Linux distributions use different package managers (dnf, zypper, apk, etc.). If you’re unsure how to install a package, command-not-found.com can help. Simply enter the name of a command, and it will suggest the correct installation command for various distributions.

Editing Files

A key part of using the command line is working with text files, whether editing configurations, writing scripts, or jotting down notes. To do this, we use text editors: programs designed for editing plain text.

Linux offers both graphical text editors (such as Gedit, Kate, and VS Code) and terminal-based editors (like Nano, Vim, and Emacs). While graphical editors provide a familiar point-and-click interface, terminal-based editors are powerful for quick modifications, remote work, and scripting.

nano is a simple but powerful text editor that runs inside the terminal. Let’s go step by step through creating and editing a file.

To open an existing file or create a new one, use:

nano my_file.txt

After running this command, you’ll see a blank screen or text from an existing file. This is nano’s editor, where you can type freely.

Once you’ve edited your file, here’s how to save and close it:

You’ve just created and edited a text file using the terminal!

While nano is easy to use, some users prefer Vim or Emacs, as they offer greater efficiency for experienced users. You might find these editors more intuitive once you get used to them.

If you're curious, consider experimenting with them in the future—you might find one suits your workflow better.

Advanced File Manipulation.

Go ahead and create a new file called fruit.txt.

nano fruit.txt

In this file, add some lines of text. Preferably things relating to fruit.

apple
banana
cherry
Apple pie
Banana smoothie
grape
orange

Now save and exit the file (Crtl + X, Y, then Enter).

The grep command is used to search for specific text within a file or output. It’s incredibly useful for finding lines that match a pattern.

The basic use of grep is to search for a word inside a file. Try:

grep "apple" fruit.txt

This will return any and all lines from the file that contain the string "apple." Notice how the line "Apple pie" is missing, this is because grep is case sensitive by default, meaning "apple" and "Apple" are treated differently because of the capitalization of the letter 'A'.

To make the search case-insensitive, use the -i flag:

grep -i "apple" fruit.txt

This will match both "apple" and "Apple pie".

To find lines that do not contain a specific word, use the -v option:

grep -v "banana" fruit.txt

This prints every line except those containing "banana".

A pipe (|) is a special operator that lets us send the output of one command directly into another. This allows us to chain commands together.

Let’s start with a simple use case—searching for a word inside a file using cat and grep:

cat fruit.txt | grep "apple"

What happens here?

This means that instead of grep searching a file directly (grep "apple" sample.txt), it receives its input from cat.

Pipes can connect multiple commands together. Here’s an example of finding .txt files in a directory and counting them:

ls | grep ".txt" | wc -l

Let’s break it down:

The tee command allows us to both display output and write it to a file at the same time. For example:

ls | tee files_list.txt

This command:

If you want to append rather than overwrite a file:

ls | tee -a files_list.txt

The -a option ensures new output is added instead of replacing existing content.

Reading The Manual

Linux includes built-in manual pages (man), which provide detailed documentation for commands, including their purpose, options, and usage examples. Whenever you’re unsure how a command works, man is the first place to check.

To view the manual for a specific command, type:

man ls

This opens the manual for ls. You’ll see a formatted document explaining what ls does, followed by lists of options and examples.

Once inside a manual page, use the following keys to navigate:

If you don’t remember a command but know what it’s related to, use:

man -k "directory"

This searches all manual pages for commands related to "directory." For example, the output might include:

ls (1)             - list directory contents
pwd (1)            - print name of current/working directory
cd (1)             - change the working directory

Manual pages are organized into numbered sections, such as:

If multiple manual pages exist for a command, specify the section:

man 5 passwd

This opens section 5 (file format details) for passwd, instead of the standard section 1 (user command).

If you just need a quick description of a command without opening the full manual, use:

whatis grep

This displays:

grep (1) - print lines matching a pattern

It’s a shortcut for checking what a command does before reading its manual.

Scripting

A script is a sequence of commands stored in a file and executed as a single unit. Instead of manually typing commands one by one, a script allows you to automate tasks, streamline workflows, and create reusable processes. Think of it as writing down instructions for the computer to follow step by step.

A script is just a text file that contains commands. Let’s create one and have it print "Hello, World!" to the terminal.

  1. Creating the Script File

Run:

nano hello.sh
  1. Adding the Script Code

Inside Nano, type the following:

#!/bin/bash

echo "Hello, World!"

Let’s break this down:

  1. Saving and Exiting

Press Ctrl + X, then Y, then Enter to save the file.

  1. Making the Script Executable

Before we can run our script, we must give it permission to be executed (Also known as being run.).

Linux uses a permission system to control who can read, write, and execute files. The chmod command lets you change these permissions.

Before modifying permissions, check the current settings with:

ls -l hello.sh

You'll see output like this:

-rw-r--r-- 1 user group 24 Apr 20 21:05 hello.sh

The file permission string shown in ls -l, like -rw-r--r--, is divided into four parts:

To make the script executable for all users, run:

chmod +x hello.sh

Now, check the file again:

ls -l hello.sh

You'll see:

-rwxr-xr-x 1 user user  24 Apr 20 21:07 hello.sh

The x is now present, meaning the script can be executed.

Now, you can enter:

./hello.sh

You should get "Hello, World!" as output, meaning that the script has run successfully.

Variables

A variable is a way to store information in a script so that it can be used or modified later. Think of it like a labeled container holding a piece of data.

Let’s update hello.sh to use a variable. Open the file in nano and change it to look like this:

#!/bin/bash

user_name="Alice"

echo "Hello, $user_name!"

You can try it out by running the script again via ./hello.sh.

Linux also provides predefined variables that influence system behavior. These are known as environment variables, and they help configure the operating system and user sessions.

One such important environment variable is $PATH. The $PATH variable determines where the system looks for executable files when a command is entered. When you type a command, Linux searches the directories listed in $PATH to locate the corresponding executable.

The $PATH variable contains a list of directories, separated by colons (:). Each of these directories is a location where the system searches for commands. You can view your current $PATH setting by running:

echo $PATH

You'll see output similar to this:

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

Each of these directories is a place where executable programs are stored. When you enter a command like ls or grep, Linux looks through the directories in $PATH until it finds the program. These programs are simply executable files just like the script we've created. If we were to include the script in our $PATH variable, we could run it from anywhere just like we can with ls or grep.

We can actually do this quite easily. First, let's create a new directory where we can store our own executable files.

mkdir ~/bin

Next, we need to move our script into that new directory.

mv hello.sh ~/bin/

Update $PATH to include our ~/bin/ directory.

export PATH=$PATH:~/bin

In this line, we have set up the path variable the same way we would any other variable, with the exception that we are telling it to include contents of itself as a part of the data we are assigning to it.

These changes will only be in effect for the current terminal session. If you were to end the session by closing the terminal or by typing exit, the changes made to the $PATH variable would be lost. We can make this change permanent by editing a file called ~/.bashrc.

The ~/.bashrc file is a configuration file for the shell that runs every time a new interactive shell session is started. It allows users to customize their shell environment. If we were to include our prior export PATH=$PATH:~/bin line inside of this file, every new Bash session would automatically update the $PATH variable to include ~/bin.

You can add this line to the file by manually editing it with nano ~/.bashrc or you could simply append it to the end of the file with echo 'export PATH=$PATH:~/bin' >> ~/.bashrc. Be careful to use two '>' symbols and not just one. Using only one would overwrite the entire file with just our new line!

To make the changes to our ~/.bashrc file take place in the ongoing shell session, run source ~/.bashrc

Take note of the '.' character at the start of the file name in ~/.bashrc. This dot leading the file name means that the file is hidden. If you were to run ls ~, you would not see ~/.bashrc in the output, nor any of the other hidden files in the ~ directory. Try running ls with the -a option to see hidden files. I.e ls -a ~.

Now that we've added our custom script to $PATH, let's explore how we can verify its location using two handy Linux commands: which and whereis. These commands help us find executable files and system utilities, making them useful for troubleshooting and understanding command locations.

The which command searches for executables in the directories listed in $PATH. It tells us which version of a command is being executed when we type it in the terminal. This is especially helpful when multiple versions of a program exist.

Try running:

which pwd

This shows us the location of the pwd command.

which hello.sh

Should output the path to our script in ~/bin. It will show the absolute path.

Administrative Tasks

The useradd command allows administrators to create new user accounts. When a new user is added, Linux generates a home directory (depending on system settings) and assigns default configurations. Example:

To create a user named john, use:

sudo useradd -m john

After adding a user, it’s a good practice to set a password:

sudo passwd john

Linux prompts the administrator to enter and confirm a new password.

Groups help organize users, making it easier to assign permissions collectively. To create a new group, use the groupadd command.

sudo groupadd developers

Now, users can be added to the developers group, granting them access to shared resources.

The id command displays a user’s unique ID (UID), group ID (GID), and associated groups.

To check details for the user john, run:

id john

Expected output:

uid=1001(john) gid=1001(john) groups=1001(john)

Users can be added to groups using the usermod command:

sudo usermod -aG developers john

To verify the user's group membership:

groups john

This will list all groups the user belongs to.

Efficient user and group management ensures proper access control, security, and organization within a Linux system. By assigning users to specific groups, administrators can regulate file access and simplify permission management.

Process Management

A process in Linux is a running instance of a program. Whether it’s a system service, a user application, or a background script, each process has an ID and consumes system resources like CPU and memory. Managing processes is crucial for maintaining system performance, troubleshooting issues, and terminating applications.

Linux provides several commands to monitor and manage processes.

The ps command displays a list of currently running processes and their details, such as process IDs (PIDs), CPU usage, and memory consumption.

To view processes running in the current terminal session:

ps

Expected output:

  PID TTY          TIME CMD
 1234 pts/0    00:00:02 bash
 5678 pts/0    00:00:01 vim

For a more detailed view, use:

ps aux

This provides system-wide process details, including CPU and memory usage.

If you need to end a process (Useful in the case where a process becomes unresponsive or etc), it can be terminated using the kill command. This command sends a termination signal to the specified process ID (PID).

To stop a process with PID 5678:

kill 5678

For a forceful termination, use:

kill -9 5678

The -9 flag sends a "SIGKILL" signal, immediately stopping the process.

Linux provides multiple signals for terminating or interacting with processes. The kill command works by sending these signals, each with a different effect. Here are a few common ones:

Different programs respond to signals in different ways

The top command provides a dynamic, real-time view of running processes, displaying system resource usage for CPU, memory, and load averages.

Simply run:

top

You'll see an interactive list where processes update continuously. Press q to exit.

The htop command is a more user-friendly alternative to top, offering color-coded output, process management, and better visual representation. Example:

To start htop (if installed):

htop

Unlike top, htop allows interactive navigation with arrow keys, making it easier to sort and manage processes.

Daemons

In Linux, daemons are background processes that run independently of direct user interaction. Unlike regular programs, daemons typically start at system boot and continue running silently, performing essential tasks such as managing network connections, scheduling jobs, or handling system logging. You'll often recognize daemons by names ending in d, like sshd (Secure Shell Daemon)

The init system is a fundamental component of Linux, responsible for managing the startup sequence and overseeing system processes after boot. It initializes services, sets up system resources, and ensures that daemons function correctly. Essentially, the init system acts as the first process that runs when the system starts—often assigned PID 1.

Over time, Linux has seen multiple init systems, such as SysVinit and Upstart, each with its own approach to managing processes. However, Systemd has become the dominant init system across modern Linux distributions. Systemd introduces parallelized service startup, better logging, and efficient resource management, making it the preferred choice for most Linux distributions today. While some systems still use alternative init methods, Systemd’s widespread adoption has shaped how modern Linux systems handle boot and service management.

Since different Linux distributions may use different init systems, it's useful to confirm which one your system is running. You can check this using a few simple commands.

  1. Checking the Process with ps

Because the init system is always the first process (PID 1), you can use ps to inspect it:

ps -p 1 -o comm=

Most likely, your system is using Systemd. In this next section, we will go over how to manage Systemd. If you're not using Systemd, refer to the proper documentation for your init system.

Systemd provides the systemctl command, which allows users and administrators to manage system services (also known as daemons).

To verify whether a service is running, use:

sudo systemctl status service-name

For example:

sudo systemctl status sshd

This command provides details about the service’s current state, whether it's active (running) or inactive (stopped). The output also includes logs showing recent activity, which can be useful for troubleshooting.

Once you’ve checked a service’s status, you can manually start or stop it.

sudo systemctl start sshd 

Will start the sshd service.

sudo systemctl stop sshd

Will stop the sshd service.

Rather than manually starting a service every time, you can set it to start automatically on system boot.

sudo systemctl enable `sshd`

Will make it so that sshd is run each time the system boots.

sudo systemctl disable `sshd`

Will have the opposite effect. Making it so that sshd is not started at boot time.

Conclusion

Now that you've explored the fundamental aspects of the Linux command line, you're well on your way to mastering one of the most powerful tools available to developers, administrators, and everyday users alike.

But this is just the beginning. The Linux command line is vast, offering countless opportunities beyond what we’ve covered here. If you're eager to continue exploring, here are a few fascinating tricks and tools worth checking out:

It may feel overwhelming now, but every Linux expert started as a beginner. The real learning happens when you experiment, make mistakes, and practice. As you continue to use the command line, concepts that once seemed complex will start to feel natural, and soon, you'll be navigating Linux like a pro.

So keep exploring, keep experimenting, and embrace the mindset of continuous learning. You are well on your way to becoming a GNU/Linux power user—and the possibilities ahead are limitless.

Comments

(Comments must be approved by a moderator.)





captcha imgage


No comments yet. Be the first to leave a comment!