Basic Bash Commands
Basic Bash Commands
ls Command
The ls command lists all files and directories in the current directory. It provides valuable information about the files and
directories within a specified directory, such as their names, permissions, timestamps, and more.
The syntax of the ls command is: ls [options] [file|dir]
The most commonly used options are:
Option Description
-a By default, ls omits hidden files from the output. To include hidden files, specify the -a option.
Modifies the output to display file sizes in a more human-friendly format. Instead of using bytes, the -h option
-h
formats the sizes using units like kilobytes (KB), megabytes (MB), gigabytes (GB), etc.
The following example shows the output of the ls -l command:
cd Command
The cd command changes the current directory to the directory specified as an argument to the command. It allows users
to move to different locations in the file system and access files, directories, and resources in those directories.
The command is essential for efficient command-line navigation and for executing commands or accessing files in
specific directories without having to provide full paths each time.
The syntax for the cd command is:
cd [directory]
pwd Command
The pwd command prints the path of the current working directory. It is useful when you need to find your way within the
Linux file system or to pass the working directory in a Bash script.
The syntax for the pwd command is:
pwd [options]
2. File Manipulation
Use the commands listed in this section for file manipulation, including file creation, copying, moving, renaming,
deleting, searching, modifying files, etc.
cat Command
Display contents of a file
The cat command is short for concatenate. It displays the contents of a file or files in the terminal without having to open
the file for editing. It is convenient for viewing the contents of small text files, joining together and displaying multiple
files' contents, or piping the output into other commands for further processing.
The syntax for the cat command is:
The touch command creates a new, empty file or updates the timestamp of an existing file. The command is useful when
you want to create a new file without any content or when you need to modify the timestamps of a file to the current time
without changing its contents.
The syntax of the touch command is:
touch [file]
rm Command
The rm command removes files or directories to free up storage space and organize the file system.
The syntax for the rm command is:
Recursive deletion, which removes directories and their contents, including subdirectories and files within them
-r
Use this option to delete a directory and everything inside it.
Forcefully remove files and directories without asking for confirmation, even if they are write-protected or
-f
otherwise restricted. It suppresses most error messages that would typically prompt for confirmation.
mkdir Command
The mkdir command creates a new, empty directory. mkdir also allows users to set permissions, create multiple
directories at once, and much more. The tool is handy when setting up a new project structure or when you need to create
nested directories to maintain a well-organized file system.
The syntax of the mkdir command is:
A necessary option if you want to create subdirectories as well. Without the -p option, the output is an error if
-p
one of the directories in the string does not exist.
-m Sets the permissions (mode) for the newly created directory. For [mode], specify the permission mode using t
[mode] octal representation, like 777, to add read, write, and execute permission for all users.
rmdir Command
The rmdir command removes only empty directories via the terminal. It is useful when you need to clean up the file
system by removing empty directories that are no longer needed, which helps maintain a tidy directory structure.
The syntax for the rmdir command is:
The command is simple and doesn't have many options since it is only used to remove empty directories. The most
common option is -p, which removes the specified directory and its parent directories if they become empty as a result.
For example:
cp Command
The cp command is used to copy files and directories using the CLI. It enables users to duplicate files and directories
within the same location or to a different one while preserving their content, permissions, and attributes.
The cp command is essential when creating backups, replicating data, or organizing files across different directories. The
syntax is:
Enforces recursive mode. It allows the cp command to copy the specified directory and its entire contents,
-r
including subdirectories and their contents.
-i Enforces the interactive mode, prompting the user for confirmation before overwriting any existing files.
-n The -n option stands for no clobber and prevents the cp command from overwriting existing files.
The following example shows how the interactive mode prompts the user for confirmation before overwriting an existing
file:
mv Command
The mv command allows users to move directories and files within the same file system, effectively changing their path.
Additionally, it can also rename files or directories, providing a way to organize and manage data within the file system
efficiently.
The syntax for the mv command is:
Enforces the interactive mode and prompts the user for confirmation before overwriting any existing files at the
-i
specified [destination].
-n The -n option stands for no clobber and prevents the mv command from overwriting existing files.
The following example shows how to use the mv command interactive mode and move a file to a different directory:
find Command
The find command searches for files or a specific string of characters in a directory hierarchy. It allows users to search the
entire file system or specified directories for files or strings based on factors such as name patterns, file types, sizes,
modification times, and more.
The syntax of the find command is:
find [location] [expression] [options]
[location] is the directory where the search will begin. If not specified, the search starts from the current
directory.
[expression] is used to combine multiple search criteria using logical operators (-and, -or, -not). It can be used to
create complex search conditions.
The most common command options are:
Option Description
Used to search for files and directories based on their names. Provide a pattern or a complete name as an
-name
argument to the -name option, and the find command locates and displays the files or directories that matc
[pattern]
the specified name.
-type [file Filters files based on their type. Provide a single-character argument to the -type option to indicate the type
type] file you're searching for. For example, f are regular files, d are directories, l are symbolic links, etc.
Searches for files based on their size. The command accepts modifiers
-size [size]
like c (bytes), k (kilobytes), M (megabytes), etc.
The following example shows how to find all .txt documents larger than 1 kilobyte:
grep Command
The grep command searches files for lines that match a given regular expression. It is particularly valuable when
analyzing log files, code files, or any text-based data since it helps quickly identify relevant information and extract useful
insights from large amounts of text.
The command syntax is:
[search pattern] is the text or regular expression you're searching for. It can be a simple string or a more complex
regular expression.
[file] are the files in which you want to search for the pattern. You can specify one or multiple files. If no files are
specified, grep reads from standard input.
For additional functionality, use the following options:
Option Description
Enforces a recursive search and searches through directories and their subdirectories. With this
-r
option, grep searches for the specified pattern in files within the specified directory and all its subdirectories.
Displays only the file names that contain the specified pattern instead of showing the matching lines within thos
-l
files.
The following example shows how to search for a string in a specific file and ignore case:
sort Command
The sort command sorts the lines in text files in a specific order, for example, alphabetically or numerically, which
facilitates data organizing and analysis. The command is particularly useful when dealing with large datasets, logs, lists,
or any text-based information that needs to be presented in a systematic and orderly manner.
The syntax for the sort command is:
Used to sort lines of text based on numerical values. When applied, the sort command interprets the data
-n
numbers and arranges them in ascending order.
-r Used to reverse the sorting order, causing sort to arrange the lines in descending order instead of ascendin
Used to sort the lines based on a specific field within the lines of text. Provide an argument to the -k optio
-k
in the form of start_field,end_field, where start_field and end_field are the fields you want to use for
[argument]
sorting.
In the following example, we use the sort command to reverse the sorting order in a file in descending order:
4. Changing Permissions
Changing file permissions in Linux involves modifying the access rights of a file or directory for different user categories
(owner, group, and others).
chmod Command
The chmod command modifies the permissions of files and directories. It allows users to specify the access level that the
owner, group, and other users have to a file or directory. The command assigns read, write, and execute permissions using
symbolic or octal notation. The tool is particularly useful for securing sensitive data, controlling user access to files, and
managing script and program execution.
The syntax for the chmod command is:
[mode] is the permission mode you want to set for the specified [file/s] or directory. Use symbolic notation (e.g., u+rwx)
or octal notation (e.g., 755).
The commonly used options are:
Option Description
chmod recursive mode, applies the permission changes to the specified file or directory but also to all of its
-R
subdirectories and their contents.
The verbose option makes chmod display a message for each file or directory it modifies, showing the permissi
-v
changes.
chown Command
The chown command changes the ownership of files and directories. It allows users with appropriate permissions to
reassign the ownership of a file or directory to a different user or group. The command is useful when system
administrators need to transfer files between users or change the ownership of system files. This ensures proper access
control and data management in the file system.
The chown command syntax is:
owner is the name or numeric user ID of the new owner you want to assign to the file(s) or directory.
group is the name or numeric group ID of the new group you want to assign to the file(s) or directory. Omitting
this part keeps the group unchanged.
The commonly used options are:
Option Description
Recursive mode, applies ownership changes to the specified file or directory but also to all its subdirectories an
-R
their contents.
The verbose option makes chown display a message for each file or directory it modifies, showing the changes
-v
makes to the ownership.
tar Command
The tar command is an archiving tool for creating, extracting, and manipulating archive files called tarballs. It combines
multiple files and directories into a single file, preserving their structure and permissions. The command helps create
backups, distribute and transfer groups of files efficiently.
The syntax for the tar command is:
[archive-file] is the name of the archive file you want to create, extract from, or manipulate. Omitting this
causes tar to default to using the standard input/output.
[file | dir …] are the files and/or directories you want to include in the archive. You can specify one or more
file/directory names. When creating an archive, list the files and directories you want to include. When extracting,
this part is usually omitted, and the command extracts the contents of the archive into the current directory.
The common tar options are:
Option Description
-f [archive- Use the -f option to specify the name of the archive file you're creating or manipulating. For [archive-file
file] specify the name of the archive you want to work with.
gzip Command
The gzip command is a file compression utility that uses the gzip compression algorithm to reduce the size of files while
preserving the content. The command helps you save storage space or accelerate file transfer over networks.
gzip is commonly used to compress log files, text documents, configuration files, and other text-based data files.
The gzip command syntax is:
Decompress a compressed file. Using this option reverses the compression process performed by gzip and resto
-d
the original file to its uncompressed state.
Use the -k option to retain the original files when performing an operation. It's useful when you want to preserv
-k
both the original and processed versions of a file without overwriting the original file.
Zip a file or directory structure (to reduce file size and increase
file transfer speed)
# Specify the zip name and then the names of the file(s) to be zipped
$ unzip shopping.zip
head Command
The head command is a Bash utility that allows users to preview the beginning section of a text file or input stream. Use a
filename or input source as an argument to display the first few lines of the content and see a quick overview of the file's
structure, formatting, or initial data.
The command is particularly useful for assessing log files, configuration files, and large documents, providing fast access
to content without processing the entire file.
The syntax of the head command is:
echo Command
The echo command is a built-in Bash utility that displays text or variables in the terminal as the standard output. It is
useful for generating output messages, displaying variable values, or in Bash scripts.
echo allows users to perform basic string manipulation, create prompts, generate user notifications, and create formatted
output. The command is essential for both interactive use and automation.
The syntax is:
Instructs echo not to print the trailing newline character after displaying the specified text or variable. By
-n
default, echo adds a newline character at the end of the output.
-e Enables the interpretation of certain escape sequences within the text or variable being echoed.
The following example shows how to use echo to print a string and a variable in the standard output:
man ls
Display the manual for a command
$ man ls
NAME
ls – list directory contents
SYNOPSIS
ls [-@ABCFGHILOPRSTUWabcdefghiklmnopqrstuvwxy1%,] [--color=when] [-D format] [file ...]
DESCRIPTION
For each operand that names a file of a type other than directory, ls displays its name
as well as any requested, associated information. For each operand that names a file of
type directory, ls displays the names of files contained within that directory, as well
as any requested, associated information.
# And so on ...
date Command
The date command is a Bash utility that prints the system date and time. It also allows users to format and manipulate date
and time information. The date command is useful for timestamping files, generating time-sensitive output in scripts,
setting system clocks, calculating time intervals, and more.
The date command syntax is:
[+format] is an optional argument that specifies the output format of the date and time. The format string can include
various placeholders that represent different components of the date and time (e.g., %Y for years, %m for
months, %H for hours, %M for minutes, etc.).
The common command options are:
Option Description
df Command
The df command is a Bash utility that allows users to check disk space usage on a filesystem basis. When invoked without
arguments, df provides a summary of disk space usage across all mounted filesystems.
The command syntax is:
df [options] [filesystem]
[filesystem] is an optional argument that allows you to specify filesystems. df then displays information only for those
filesystems. Omitting these arguments causes df to display information for all mounted filesystems.
The common options are:
Option Description
du Command
The du command estimates and displays the disk space usage of files and directories. By default, du provides the space
used by the specified files and directories in bytes. It is useful for identifying which files or directories consume the most
disk space on a filesystem.
The du command syntax is:
du [options] [file]
[file] is an optional argument that allows you to specify specific files or directories to analyze. If no file or directory path
is provided, du analyzes the current directory by default.
The commonly used options are:
Option Description
-s Display only the total size for each argument (directory or file).
The following image is a partial du command output:
ps Command
The ps command lists processes currently running on the system. By default, it displays a list of processes associated with
the current terminal session, including their process IDs (PIDs), resource utilization, and other attributes. Use the tool for
monitoring system activity, identifying misbehaving processes, investigating resource consumption, and managing
process-related tasks.
The command syntax is:
ps [options]
The [options] allow users to customize the output to show detailed information about all processes on the system, filter
processes based on user or attributes, and format the output.
The most common options are:
Option Description
Display information about all processes on the system, regardless of whether they are associated with the curren
-e
terminal session.
Change the output format to provide a more detailed and comprehensive view of each process. This includes
-f information on which user started the process, the process ID (PID), the parent process ID (PPID), the CPU and
memory usage, the terminal associated with the process, and more.
The following example shows the ps command output:
history Command
The history command is a Bash utility that displays a list of recently executed commands within a terminal session. It
provides a chronological record of command-line inputs, along with their corresponding line numbers.
The command is useful for recalling and re-executing previously used commands, streamlining repetitive tasks, and
maintaining a record of your actions for reference or documentation.
The command syntax is:
history [options]
-c Clears the command history, deleting all previously executed commands from the history list.
Writes the current history list to the history file (~/.bash_history by default) and saves any changes made during
-w
the session.
The following example shows a partial history command output:
exit Command
The exit command is a Bash utility used to end a terminal session or script. Running the command in the command-line
interface instructs the shell to terminate the current session or script. The action closes the terminal window or returns
control to the parent process.
The command is useful for concluding tasks, scripts, or interactive sessions, and it ensures that all resources are properly
released and processes are terminated.
The command syntax is:
exit [n]
[n] is an optional argument that specifies the exit status that the shell or script returns after termination.
7. Pipe Utility
The | (pipe) utility is a powerful tool that allows users to connect the standard output of one command to the standard
input of another, thus enabling the flow of data between commands. It is beneficial when performing tasks that involve
multiple commands, data transformation, filtering, or data aggregation.
The basic syntax is:
[command1] | [command 2]
In the following example, the output of the echo command is piped into grep, which filters out the months that start with
"J":