Bash Scripting Cheatsheet

Linux & SBC 17 Th01 2023

BASH acronym for The GNU Bourne-Again SHell is an interface for you to execute statements, either at the interactive BASH prompt or via BASH scripts. It can run in interactive mode and also run in non-interactive mode when executing scripts. Scripts are lists of commands stored in a file. When you execute a script, all commands are executed one after another.

This Bash cheat sheet will show you all useful bash commands that any network or system admin can use as a quick reference.

Bash Scripting Basics

Here, we list some basic bash syntax with a brief explanation. It is a good starting point if you are a beginner.

SyntaxExplanation
#!/bin/bashUsed to tell the operating system the path it should use to interpret the file.
bash file.shUsed to execute the script in the terminal.
./file.shUsed to execute the script if it is executable.
#Used to make comments in the script.
&&logical AND operator.
| |logical OR operator.
$#Used to expands the number of arguments passed to the script.
$0Used to expands to the name of the shell.
$1, $2Used as an input param­eter that you can add when running script.
exit [0-255]Used to exit the script and return the number from 0 to 255.
$Used for parameters and variables.
()Used for running commands in a subshell.
$()Used to save the output of commands.
(())Used for arithmetic.
$(())Used to retrieve the output of arithmetic expressions.
[]Used in filename expansion and string manipulation.
<( )It is very similar to a pipe and used for process substitution.
{ }Used to expand sequences.
${ }Used for string manipulation and variable interpolation.
|Used to run multiple commands together.|
>Used to send output to a file.
>>Used to append output to a file.
;Used to separate multiple commands.
<Used to get input from a file.
~Expands to the home directory.
~/.bashrcRead by every non-login shell.
/etc/profileExecuted automatically at login.

File Test Operators

Here, we will list some helping testing operators for permissions, size, date, file type, or existence in the bash script.

OperatorsExplanation
-eTo test if a file exists.
-fTo test if a given file is a regular file.
-dTo test if the file is a directory.
-bTo test if the file is a block device.
-sTo test if the file is not zero sizes.
-LTo test if the file is a symbolic link.
-STo test if the file is a socket.
-rTo test if the file has read permission.
-wTo test if the file has write permission.
-xTo test if the file has execute permission.
-gSet group id on file or directory.
-uSet user id on file or directory.
-kSet a sticky bit.
-OYou are the owner of the file.
f1 -nt f2file f1 is newer than f2.
f1 -ot f2file f1 is older than f2

Comparison Operators

Comparison operators are used in bash to compare two strings to check if they are equal or not. Here, we will list some comparison operators including, string, and integer operators.

Integer Operators
OperatorsExplanation
-eqis equal to
-neis not equal to
-gtis greater than
-geis greater than or equal to
-ltis less than
-leis less than or equal to
String Operators
OperatorsExplanation
=is equal to
==is equal to
!=is not equal to
<less than
<=is less than or equal to
>greater than
>=is greater than or equal to
-zstring is null
-nstring is not null

Regular Expressions

Regular expressions are shortened as ‘regexp' or ‘regex'. They are strings of characters that define a search pattern. It can be used as a search or search & replace operation.

Expressions
.Matches any single character.
?The preceding item is optional and will be matched, at most, once.
*The preceding item will be matched zero or more times.
+The preceding item will be matched one or more times.
{N}The preceding item is matched exactly N times.
{N,}The preceding item is matched N or more times.
^Matches the empty string at the beginning of a line.
$Matches the empty string at the end of a line.
[a-d]Matches any one character in the range a-d.

Loops and Conditions

A loop is a statement in a bash programming language that allows code to be repeatedly executed. You can set specific conditions during the script execution.

Loops
if then fiUsed to test a condition.
if then else fiUsed to test a condition and use a fallback if the test fails.
if then elif else fiUsed to test a condition and use a fallback if all tests fail.
for do doneIterate over a list of values.
while do doneUsed to performs a given set of commands an unknown number of times as long as the given condition evaluates to true.
until do doneUsed to execute a given set of commands as long as the given condition evaluates to false.
sleep timeWait for a specified amount of time before continuing through the script.
breakUsed to exit from the while or for loop but continue the rest of the script.
continueUsed to skip the current iteration of a loop and continue to the next iteration of the loop.

Bash Arrays and Functions

Array
array=("elements of array")Used to create an array of strings.
${array[0]}Used to get the first element of the array.
${array[*]}Used to get all values in the array.
${array[-1]}Get the last value in the array.
${array[@]}Expand all of the array elements.
shiftMove argument from $2 to $1.
function() { content-of-function }Used to define a function.
aliasUsed to list all aliases defined in the current session.
alias alias='any command'Used to define an alias.

Common Utilities and Switches

This cheat sheet will show you the most useful commands and switches to help you in your network and system administration.

Commands
ls -lList files by type and permission.
ls -aList all files, including hidden files.
pwdDisplay current working directory.
whoamiWho you are logged in as.
lastDisplay last user logins information.
find /home -name *.txtSearch all text files in /home directory.
find . -size 10k -printFind all files greater than 10k in the current directory.
egrep "(foo|bar)" file.txtFind the words foo and bar in file.txt.
sed s/foo/bar/g file.txtFind the word foo and replace it with a bar in file.txt.
locate file.txtFind the location of the file.txt quickly.
grep foo file.txtSearches the word foo in file.txt.
ps -efTo check all running services.
netstat -antTo check all network connections.
netstat -entTo check established network connections.
ifconfigTo check all network interfaces, IPs, and Mac addresses.
pingUsed to check host reachability.
nslookupUsed for DNS query.
sshUsed to login remote Linux system.
scp -r dir user@remote-ip:/opt/Copy all files and directories recursively from the local system to a remote system.
scp -r user@remote-ip:/opt/ dir/Copy all files and directories recursively from the remote system to a local system.
rsync -avz localdir user@remote-ip:/backupSynchronize files/directories between the local and remote systems.
df -hShows free and used space on mounted filesystems.
du -shShows total disk usage of the current directory.
free -mShow free and used memory and swap space.
lsofLists files opened by running processes.
chown user:group filenameChange the owner of the file and directory.
chmod ugo file.txtChange the user, group, and other permis­sions for file.txt.
kill pidKill any running process.
passwd usernameUsed to set or reset the user password.
topDisplay all running processes, memory usage, cpu usage in real-time.

Shell Builtins

Builtin commands are contained within the shell itself. They called from a shell, that is executed directly in the shell instead of an external executable program.

Builtins
.Used to reads and runs commands from a designated file in the current shell.
aliasUsed to define an alias for a specific command.
bgRun a job in background mode.
bindUsed to bind a keyboard sequence.
breakUsed to exit from a running loop in script.
cdChange the directory to another directory.
commandRun a specific command without the normal shell lookup.
continueResumes the next iteration of the loop in script.
declareUsed to declare a variable.
dirsShows a list of all remembered directories.
disownRemove a job from the job table.
enableUsed to enable or disable built-in command.
execReplace the shell process with the specified command.
exitUsed to exit the shell with an exit status.
exportUsed to set a variable available for sub-process.
fcSelect a list of commands from the history list.
fgRun a job in foreground mode.
hashUsed to find and remember the full path of the specified command.
helpUsed to display the help file.
historyList the history of all commands.
jobsList all active jobs.
logoutUsed to exit from the current shell.
pwdDisplay the path of the current working directory.
readRead one line from STDIN and assigns it to a variable.
popdRemoves entries from the directory stack.
pushdAdd a directory to the directory stack.
printfDisplays text in a formatted string.
sourceRead and executes commands from a specified file in the current shell.
timesDisplays the accumulated user and system shell time.
waitMake the shell wait for a job to finish.

Other Bash scripting cheatsheet

Bash scripting cheatsheet
Variables · Functions · Interpolation · Brace expansions · Loops · Conditional execution · Command substitution · One-page guide to Bash scripting

Tags

Tony Phạm

Là một người thích vọc vạch và tò mò với tất cả các lĩnh vực từ khoa học tự nhiên, lập trình, thiết kế đến ... triết học. Luôn mong muốn chia sẻ những điều thú vị mà bản thân khám phá được.