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
Syntax
Explanation
#!/bin/bash
Instructs the operating system to interpret the file using the given path
bash file.sh
Triggers the execution of the script in the command line
./file.sh
Executes 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
$0
Displays the name of the shell or shell script
$1, $2
Acts 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
~/.bashrc
File accessed by each non-login shell
/etc/profile
Auto-executed at user login
File Test Operators
Operators
Explanation
-e
Evaluates if a file or directory exists
-f
Confirms if a provided file is a regular file
-d
Assesses if the input file is actually a directory
-b
Tests if the input file is a block device
-s
Validates if the file has a size greater than zero
-L
Examines if the file is a symbolic link
-S
Checks whether the file is a socket
-r
Tests for read permissions on the file
-w
Determines if the file holds write permissions
-x
Examines if the file has execute permissions
-g
Applies the group id on file or directory
-u
Assigns the user id on file or directory
-k
Sets the sticky bit on a file or directory
-O
Verifies if the user is the owner of the file
f1 -nt f2
Assesses if file f1 is newer than file f2
f1 -ot f2
Evaluates if file f1 is older than file f2
Loops and Conditions
Loops
Explanation
if then fi
Tests a condition, proceeding if true
if then else fi
Tests a condition, with an alternate path if false
if then elif else fi
Tests multiple conditions, with a fallback if all are false
for do done
Iterates over a list of items
while do done
Repeats a set of commands while a certain condition is true
until do done
Executes commands until a specific condition becomes false
sleep time
Pauses the script for a specified duration
break
Exits the current loop, but allows the script to continue
continue
Skips the current iteration and moves to the next loop iteration
Comparison Operators
Integer Operators
Operators
Explanation
-eq
Denotes equality
-ne
Denotes inequality
-gt
Indicates a greater numerical value
-ge
Indicates a numerical value that is greater or equal
-lt
Indicates a lesser numerical value
-le
Indicates a numerical value that is less or equal
String Operators
Operators
Explanation
=
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
-z
Tests if the string is null or empty
-n
Tests if the string is non-null or not empty
Regular Expressions
Expressions
Explanation
.
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
Explanation
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
shift
Moves argument from the second position $2 to the first $1
function() { content-of-function }
Outlines the structure for defining a function
alias
Shows all the aliases set in the current session
alias alias='any command'
Defines a new alias for a particular command
Shell Builtins
Builtins
Explanation
.
Executes commands from a specified file in the active shell
alias
Establishes an alias for a given command
bg
Executes a job in the background
bind
Assigns a keyboard sequence to a command
break
Exits the current loop in a script
cd
Changes the current directory
command
Runs a specific command, bypassing shell function lookup
continue
Moves to the next iteration of the current loop in a script
declare
Declares a variable
dirs
Displays the stack of remembered directories
disown
Removes a job from the shell’s job table
enable
Enables or disables a built-in shell command
exec
Replaces the shell with the specified command
exit
Terminates the shell with a defined exit status
export
Makes a variable accessible to sub-processes
fc
Selects a range of commands from the history list
fg
Executes a job in the foreground
hash
Records the full path of the specified command for future use
help
Displays the help manual
history
Shows the command history
jobs
Lists all running jobs
logout
Exits the current shell session
pwd
Shows the current directory path
read
Reads a line from standard input and assigns it to a variable
popd
Removes entries from the directory stack
pushd
Adds a directory to the directory stack
printf
Prints formatted text
source
Reads and executes commands from a file in the current shell
times
Shows the accumulated user and system times
wait
Causes the shell to wait for a job completion
Common Utilities and Switches
Commands
Explanation
ls -l
Displays files with their types and permissions
ls -a
Displays all files, including hidden ones
pwd
Shows the current working directory
whoami
Reveals the username of the current user
last
Shows the latest user login information
find /home -name *.txt
Searches for all text files in the /home directory
find . -size 10k -print
Searches for all files larger than 10k in the current directory
`egrep “(foo
bar)” file.txt`
sed s/foo/bar/g file.txt
Replaces “foo” with “bar” in file.txt
locate file.txt
Finds the location of file.txt quickly
grep foo file.txt
Searches for the word “foo” in file.txt
ps -ef
Lists all currently running services
netstat -ant
Displays all network connections
netstat -ent
Shows all established network connections
ifconfig
Displays all network interfaces, IPs, and MAC addresses
ping
Tests host reachability
nslookup
Used for DNS query purposes
ssh
Logs 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:/backup
Synchronizes files/directories between the local and remote systems
df -h
Displays free and used space on mounted filesystems
du -sh
Shows the total disk usage of the current directory
free -m
Displays free and used memory and swap space
lsof
Lists files that are open by running processes
chown user:group filename
Changes the owner and group of a file or directory
chmod ugo file.txt
Modifies the permissions of file.txt for user, group, and others
kill pid
Terminates a specified running process
passwd username
Sets or resets the password for a user
top
Displays all running processes, memory usage, and CPU usage in real-time
Jamie has been an avid gamer since the release of the Amiga 500 back in the early 1990s. He's the proud owner and author of makeawebsitehub.com a site that provides webmasters with valuable resources on how to build traffic and make money online from their blogs.