This BASH cheat sheet has been designed as a quick reference guide for both beginners and advanced users. The BASH (Bourne Again SHell) environment is powerful and versatile, serving as the default shell for the majority of Linux distributions.

It allows users to interact with their operating system, automate tasks, and even write scripts to enhance functionality.

When a user types a command in BASH, the shell interprets that command and communicates with the operating system to execute it. It is essentially a bridge between the user and the operating system. BASH also features programming capabilities, allowing users to write scripts – sequences of commands – to automate repetitive tasks.

It offers variables, conditional statements, loops, and functions, making it a powerful tool for managing and interacting with a Linux system. Its flexibility and scriptability make it an essential tool for system administrators and programmers alike.

This cheat sheet comprises a range of essential commands and functionalities, including file and directory manipulation, process control, permissions management, and more. Whether you’re troubleshooting a problem, managing your system, or learning the basics, this cheat sheet is a handy resource to make your journey smoother and more efficient.

Bash Scripting Basics

#!/bin/bashInstructs the operating system to interpret the file using the given path
bash file.shTriggers the execution of the script in the command line
./file.shExecutes the script, given that it has execute permissions
#Denotes commentary within the script for user readability
&&Represents a logical AND operation
||Stands for a logical OR operation
$#Returns the count of arguments supplied to the script
$0Displays the name of the shell or shell script
$1, $2Acts as an input parameter which can be provided when launching the script
exit [0-255]Terminates the script, returning a value between 0 and 255
$Prefixed to parameters and variables for referencing
()Creates a subshell to run commands
$()Captures the output from commands
(())Allows for arithmetic operations
$(( ))Captures the result of arithmetic computations
[]Useful for file name expansion and string manipulation
<( )Enables process substitution, akin to a pipe
{ }Expands sequences
${ }Aids in variable interpolation and string manipulation
|Connects multiple commands to run in conjunction
>Redirects output to a specified file
>>Appends output to a given file
;Serves as a separator for multiple commands
<Fetches input from a specified file
~Shortcut to the home directory
~/.bashrcFile accessed by each non-login shell
/etc/profileAuto-executed at user login

File Test Operators

-eEvaluates if a file or directory exists
-fConfirms if a provided file is a regular file
-dAssesses if the input file is actually a directory
-bTests if the input file is a block device
-sValidates if the file has a size greater than zero
-LExamines if the file is a symbolic link
-SChecks whether the file is a socket
-rTests for read permissions on the file
-wDetermines if the file holds write permissions
-xExamines if the file has execute permissions
-gApplies the group id on file or directory
-uAssigns the user id on file or directory
-kSets the sticky bit on a file or directory
-OVerifies if the user is the owner of the file
f1 -nt f2Assesses if file f1 is newer than file f2
f1 -ot f2Evaluates if file f1 is older than file f2

Loops and Conditions

if then fiTests a condition, proceeding if true
if then else fiTests a condition, with an alternate path if false
if then elif else fiTests multiple conditions, with a fallback if all are false
for do doneIterates over a list of items
while do doneRepeats a set of commands while a certain condition is true
until do doneExecutes commands until a specific condition becomes false
sleep timePauses the script for a specified duration
breakExits the current loop, but allows the script to continue
continueSkips the current iteration and moves to the next loop iteration

Comparison Operators

Integer Operators

-eqDenotes equality
-neDenotes inequality
-gtIndicates a greater numerical value
-geIndicates a numerical value that is greater or equal
-ltIndicates a lesser numerical value
-leIndicates a numerical value that is less or equal

String Operators

=Specifies that two strings are identical
==Specifies that two strings are identical
!=Specifies that two strings are different
<Indicates that one string is less than another
<=Indicates that a string is less than or identical to another
>Indicates that one string is greater than another
>=Indicates that a string is greater than or identical to another
-zTests if the string is null or empty
-nTests if the string is non-null or not empty

Regular Expressions

.Corresponds to any solitary character
?The item before is optional and can be matched at most once
*Allows the item before to be matched zero times or more
+Allows the item before to be matched at least once
{N}Ensures the item before is matched exactly N times
{N,}Ensures the item before is matched at least N times
^Matches an empty string that starts a line
$Matches an empty string that ends a line
[a-d]Matches any single character between a and d inclusively

Bash Arrays and Functions

array=("elements of array")Establishes an array containing string elements
${array[0]}Retrieves the first element in the array
${array[*]}Retrieves all the elements contained in the array
${array[-1]}Retrieves the final element in the array
${array[@]}Expands and presents all elements of the array
shiftMoves argument from the second position $2 to the first $1
function() { content-of-function }Outlines the structure for defining a function
aliasShows all the aliases set in the current session
alias alias='any command'Defines a new alias for a particular command

Shell Builtins

.Executes commands from a specified file in the active shell
aliasEstablishes an alias for a given command
bgExecutes a job in the background
bindAssigns a keyboard sequence to a command
breakExits the current loop in a script
cdChanges the current directory
commandRuns a specific command, bypassing shell function lookup
continueMoves to the next iteration of the current loop in a script
declareDeclares a variable
dirsDisplays the stack of remembered directories
disownRemoves a job from the shell’s job table
enableEnables or disables a built-in shell command
execReplaces the shell with the specified command
exitTerminates the shell with a defined exit status
exportMakes a variable accessible to sub-processes
fcSelects a range of commands from the history list
fgExecutes a job in the foreground
hashRecords the full path of the specified command for future use
helpDisplays the help manual
historyShows the command history
jobsLists all running jobs
logoutExits the current shell session
pwdShows the current directory path
readReads a line from standard input and assigns it to a variable
popdRemoves entries from the directory stack
pushdAdds a directory to the directory stack
printfPrints formatted text
sourceReads and executes commands from a file in the current shell
timesShows the accumulated user and system times
waitCauses the shell to wait for a job completion

Common Utilities and Switches

ls -lDisplays files with their types and permissions
ls -aDisplays all files, including hidden ones
pwdShows the current working directory
whoamiReveals the username of the current user
lastShows the latest user login information
find /home -name *.txtSearches for all text files in the /home directory
find . -size 10k -printSearches for all files larger than 10k in the current directory
`egrep “(foobar)” file.txt`
sed s/foo/bar/g file.txtReplaces “foo” with “bar” in file.txt
locate file.txtFinds the location of file.txt quickly
grep foo file.txtSearches for the word “foo” in file.txt
ps -efLists all currently running services
netstat -antDisplays all network connections
netstat -entShows all established network connections
ifconfigDisplays all network interfaces, IPs, and MAC addresses
pingTests host reachability
nslookupUsed for DNS query purposes
sshLogs in to a remote Linux system
scp -r dir user@remote-ip:/opt/Recursively copies all files and directories from the local system to a remote system
scp -r user@remote-ip:/opt/ dir/Recursively copies all files and directories from a remote system to the local system
rsync -avz localdir user@remote-ip:/backupSynchronizes files/directories between the local and remote systems
df -hDisplays free and used space on mounted filesystems
du -shShows the total disk usage of the current directory
free -mDisplays free and used memory and swap space
lsofLists files that are open by running processes
chown user:group filenameChanges the owner and group of a file or directory
chmod ugo file.txtModifies the permissions of file.txt for user, group, and others
kill pidTerminates a specified running process
passwd usernameSets or resets the password for a user
topDisplays all running processes, memory usage, and CPU usage in real-time

More Cheat Sheets on Practically Networked

Linux Commands Cheat Sheet