This quick guide distills essential tips and tricks to get the most out of BASH, from keyboard shortcuts to task automation. We’ll explore how terminal mastery not only drives efficiency but also strengthens digital defenses in the fascinating world of cybersecurity.

Our BASH Quick Guide will help you navigate and control your system efficiently from the command line. From understanding file types and permissions to debugging, from controlling jobs to understanding regular expressions, This Guide covers it all.

The information contained in the BASH Quick Guide is valuable for casual Linux users, system administrators, information security professionals, and students preparing for a wide range of exams, from LPIC to OSCP and more.

However you choose to use it, we hope you’ve found it to be a useful resource to have on hand. 

What is Bash?

Bash (Bourne Again Shell) is a shell language built on top of the original Bourne Shell, which was distributed with V7 Unix in 1979 and became the standard for writing shell scripts. 

Today it is primary for most Linux distributions, MacOS, and has even recently been enabled to run on Windows through something called WSL (Windows Subsystem for Linux).

File Test Operators

Testing files in scripts is easy. This is where shell scripts start to show their glory! In Bash, you can test for file permissions, size, date, file type, or existence.

FLAG DESCRIPTION
-andThe file exists
-toThe file exists (identical to -e but is obsolete and out of date)
-FThe file is a normal file (not a directory or device file)
-sthe file is not of zero size
-dthe file is a directory
-bThe file is a block device.
-CThe file is a character device.
-pthe file is a pipe
-hThe file is a symbolic link.
-lThe file is a symbolic link.
-Sthe file is a socket
-tthe file (descriptor) is associated with a terminal device; This test option can be used to check whether stdin [ -t 0 ] or stdout [ -t 1 ] in a given script is a terminal
-rThe file has read permission (for the user running the test).
-wthe file has write permission (for the user running the test)
-Xthe file has execute permission (for the user running the test)
-gset-group-id (sgid) flag set on a file or directory
-orset-user-id (suid) flag set in file.
-kadhesive tip set.
-EITHERyou own the file
-GFile group ID same as yours
-Nfile modified since last read
f1 -nt f2file f1 is newer than f2
f1 -ot f2file f1 is older than f2
f1-ef f2The files f1 and f2 are hard links to the same file.
!  Not - invierte el sentido de las pruebas anteriores (devuelve verdadero si la condición está ausente).

Integer comparison operators

How to compare integers or arithmetic expressions in shell scripts.

FLAGDESCRIPTION
-eqis equal to
-neis not equal to
-gtis greater than
-geis greater than or equal to
-ltis less than
-youes menor or equal to
<es menor que - colocar entre paréntesis dobles
<=is less than or equal to (same rule as previous row)
>es mayor que (misma regla que la fila anterior)
>=is greater than or equal to (same rule as previous row)

String comparison operators

String comparison in Bash.

FLAGDESCRIPTION
=is equal to
==is equal to
!=is not equal to
<is greater than ASCII alphabetical order
>is greater than ASCII alphabetical order
-zthe string is null (i.e. of length zero)
-norththe string is not null (i.e. of length zero)

Discover: How I use Bash to automate tasks on Linux

Composite operators

Useful for Boolean expressions and is similar to && and ||. Compound operators work with the test command or can appear in single square brackets [<expr>].

FLAGDESCRIPTION
-tological and
-eitherlogical or

Job identifiers

Job control allows you to selectively stop (suspend) the execution of processes and continue their execution at a later time.

NOTATIONDESCRIPTION
%NJob number [N]
%SThe invocation (command line) of the job starts with the string S
%?SInvocation (command-line) of job contains within it string S
%%“Current” job (last job stopped in foreground or started in background)
%+“Current” job (last job stopped in foreground or started in background)
%-Last job
%!Last background process

Construction List

Provides a means to process commands consecutively and is in fact capable of replacing complex if/then/according structures

BUILD DESCRIPTION
&&and
||o

Reserved exit codes

Useful for debugging a script. The output takes integer arguments in the range 0-255.

EXIT CODE NO.DESCRIPTION
1Catchall for general errors
2Misuse of built-in shell functions
126El comando invocado no puede ejecutarse
127Command not found
128Invalid argument to exit
128+nFatal error signal “n”
130Script finished by Control-C

Signs

UNIX V system signs.

NAMENUMBERACTION DESCRIPTION
SIGHUP1exitHanging
SIGINT2exitInterrupts.
SIGQUIT3memory dumpIn peace.
SIGILL4memory dumpIllegal instruction.
SIGTRAP5memory dumpTrail trap.
SIGIOT6memory dumpIOT instruction.
SIGEMT7memory dumpMT Instruction.
SIGFPE8memory dumpFloating point exception.
SIGKILL9exitDeaths (cannot be caught or ignored).
SIGBUS10core dumpBus error.
SIGSEGVelevencore dumpSegmentation violation.
SIGSYS12core dumpBad argument for the system call.
SIGPIPE13exitHe writes on a pipe without anyone being able to read it.
SIGALRM14exitAlarm clock.
SIGTERMfifteenexitSoftware termination signal.

Sending control signals

You can use these key combinations to send signals.

KEY COMBINATIONDESCRIPTION
Ctrl+CThe interrupt signal sends SIGINT to the job running in the foreground.
Ctrl+YThe nature of delayed suspension. Causes a running process to stop when it attempts to read input from the terminal. Control is returned to the shell, the user can foreground, background or kill the process. Delayed sleep is only available on operating systems that support this feature.
Ctrl+ZThe sleep signal sends a SIGTSTP to a running program, stopping it and returning control to the shell.

Check your styt settings. Suspend and resume output are generally disabled if you use “modern” terminal emulations. The standard xterm supports Ctrl+S and Ctrl+Q by default.

File types

This is very different from Windows, but it’s simple once you understand it. I’ll expand this section soon with more context.

SYMBOL MEANING
normal file
ddirectory
ILink (symbolic)
cCharacter device
yesPlug
pNamed Pipe
bbloqueoofdispositivo

Permissions

Now you can tell what that arcane-looking string rwxrwxrwx is when you invoke ls -l

CODEDESCRIPTION
yessetuid when in user column
yessetgid when in group column
tsticky bit
0——The right of access that this place should have is not granted.
4—–rRead access is granted to the user category defined here.
2—–wWrite permission is granted to the user category defined here.
1—–xThe execute permission is granted to the user category defined here.
orUser permits
ggroup permissions
ohother permissions

Special files

Files that are read by the shell. Listed in order of execution.

ARCHIVEINFORMATION
/etc/profileLaunched automatically on login
~.bash_profile
———————
~/.bash_login
———————
~.profile
Whichever is found first is executed at login.
~/.bashrcIt is read by all non-login shells.

String manipulation

Bash supports a surprisingly large number of string operations! Unfortunately, these tools lack a unified approach. Some are a subset of parameter substitution and others fall within the functionality of the UNIX expr command. This results in inconsistent command syntax and feature overlap. MacOS’s built-in bash is from 2007 and doesn’t support many of these.

String Manipulation Table

PATTERNDESCRIPTION
${#var}Find the length of the rope.
${var%pattern}Remove from shorter end pattern
${var%%pattern}Remove from longest end pattern
${var:position}Extract substring from $var into $position
${var:num1:num2}Substring
${var#pattern}Remove from shorter front pattern
${var##pattern}Remove from longer front pattern
${var/pattern/string}Find and replace (replace only the first occurrence)
${var//pattern/string}Find and replace all occurrences
${!prefix*}Expands to variable names whose names begin with a prefix.
${var,}${var,pattern}Converts the first character to lowercase.
${var,,}${var,,pattern}Converts all characters to lowercase.
${var^}${var^pattern}Converts the first character to uppercase.
${var^^}${var^^pattern}Converts all characters to uppercase.
${string/substring/replacement}Replace the first match of $substring with $replacement
${string//substring/replacement}Replace all matches of $substring with $replacement
${string/#substring/replacement}If $substring matches the front end of $string, replace $replacement with $substring
${string/%substring/replacement}If $substring matches the end of $string, replace $replacement with $substring
expr match “$string” ‘$substring’Matching $substring* length at start of $string
expr “$string” : ‘$substring’Matching $substring* length at start of $string
expr index “$string” $substringNumeric position in $string of the first character in $substring* that matches [0 if not matched, first character counts as position 1]
expr substr $string $position $lengthExtract $length characters from $string starting at $position [0 if no match, first character counts as position 1]
expr match “$string” ‘($substring)’Extract $substring*, searching from the beginning of $string
expr “$string” : ‘($substring)’Extract $substring*, searching from the beginning of $string
expr match “$string” ‘.*($substring)’Extract $substring*, searching from the end of $string
expr “$string” : ‘.*($substring)’Extract $substring*, searching from the end of $string

Quoting

The following text shows characters that must be cited if you want to use their literal symbols and not their special meaning.

SYMBOL LITERAL MEANING
;Command separator
&Running in the background
()Command Grouping
|Tube
< > &Redirect symbols
? [ ] ~ + – @ !File name metacharacters
«’Used to quote characters.
$Variable, command or arithmetic substitution
#Start a command that ends in a line break
space tab newlineword separators

Everything between “…” is taken literally, except $(dollar)` (backquote) and » (double quote).

Everything between ‘…’ is taken literally, except ‘ (single quote).

The following are taken literally. Use it to escape anything in “…” or ‘…”

Using $ before ‘…’ or ‘…’ causes special behavior. $»…» is the same as «…» except that local translation is performed. Similarly, $’…’ is similar to $’…’ except that the quoted string is processed for escape sequences.

Command parameters

Command parameters, also known as arguments, are used when invoking a Bash script.

DOMAINDESCRIPTION
$0Name of the script itself.
$1…$9Parameter 1…9
${10}Positional parameter 10
$*It expands to positional parameters, starting from one. When the expansion occurs between double quotes, it expands to a single word with the value of each parameter separated by the first of the IFS environment variable.
$-Current options
$_The underscore variable is set when the shell is started and contains the absolute file name of the shell or script being executed as passed in the argument list. It is then expanded to the last argument of the previous command, after expansion. It is also set to the full path of each command executed and placed in the environment exported to that command. When checking mail, this parameter contains the name of the mail file.
$$shell process id
$?Exit status of the most recently executed command
$@All arguments as separate words.
$#Number of arguments
$!PID of the most recent background process

Story Expansion

Allows the use and manipulation of previous commands.

DOMAIN DESCRIPTION
!A historical replacement begins.
!!Refers to the last command.
!nRefers to the <n>-th command line.
!-nRefers to the current command line minus <n>.
!stringRefers to the most recent command starting with <string>
!?string?Refers to the most recent command containing <string> (the ending ? is optional)
^string1^string2^Quick replacement. Repeat the last command, replacing <string1> with <string2>.
!#It refers to the entire command line written so far.

Variable operations

Perform operations on variables.

EXPRESSION
${parameter:-defaultValue}
Get the default value of shell variables
${parameter:=defaultValue}
Set the default value of shell variables
${parameter:?”Error Message”}
Displays an error message if the parameter is not set

Bash Globing

Bash can’t recognize RegEx but understands globbing. The shell performs globalization of file names, while RegEx is used to search for text.

SymbolDESCRIPTION
*Matches zero or more occurrences of a given pattern
?Matches zero or one occurrence of a given pattern
+Matches one or more occurrences of a given pattern
!Negates any pattern matches — reverses the pattern so to speak

Regular expressions

Always use quotes in your RegEx to avoid globbing

OPERATOREFFECT
.Matches any individual character.
?The previous item is optional and will be matched, at most, once.
*The previous element will match zero or more times.
+The previous element will match one or more times
{N}The previous element matches exactly N times.
{N,}The previous element matches N or more times.
{N,M}The previous element matches at least N times, but no more than M times.
Represents the range if it is not the first or last in a list or the endpoint of a range in a list.
^Matches the empty string at the beginning of a line; also represents characters that are not in the range of a list.
$Matches the empty string at the end of a line.
[aoeiAOEI]Matches any 1 character in the list.
[^AOEIaoei]Matches any 1 character, which is not in the list!
[af]Matches any 1 character in the range af

In basic regular expressions, the metacharacters «?», «+», «{«, «|», «(» and «)» lose their special meaning; instead, use the backslash “?” … «)». Check your system documentation if commands that use regular expressions support extended expressions.

Character classes in BRE

A character class [:CharClass:] is a set of predefined patterns and consists of the following:

CHARACTER CLASSEQUIVALENTEXPLANATION
[:lower:][az]Lowercase letters.
[:upper:][AZ]Capital letters
[:alpha:][A-Za-z]Alphabetic letters, both uppercase and lowercase.
[:digit:][0-9]Numbers 0-9.
[:alnum:][a-zA-Z0-9]Alphanumeric: both letters (upper case + lower case) and digits.
[:xdigit:][0-9A-Fa-f]Hexadecimal digits.
[:space:][ \t\n\r\f\v]Blank space. Spaces, tabs, new lines and the like.
[:punct:]Symbols (less digits and letters).
[:print:][[:graph] ]Printable characters (spaces included).
[:blank:][\t]Space and tab characters only.
[:graph:][^ [:cntrl:]]Graphically printable characters without including spaces.
[:cntrl:]Control characters. Non-printable characters

Shell additions

Bash’s built-in shell builds are typically very (if not extremely) fast compared to external programs. Some of the built-in functions are inherited from Bourne Shell (sh); These legacy commands will also work in the original Bourne Shell.

BUILTINDESCRIPTION
:Equivalent to true.
.Reads and executes commands from a designated file in the current shell.
[It is synonymous with proof but requires a final argument of ].
aliasDefines an alias for the specified command.
b.g.Resume a job in background mode.
bindBinds a keyboard sequence to a read line function or macro.
breakExits a for, while, select, or Until loop.
built inRuns the built-in command for the specified shell.
callerReturns the context of any active subroutine calls.
case
CDChanges the current directory to the specified directory.
commandExecutes the specified command without the normal shell search.
compgenGenerates possible ending matches for the specified word.
completeShows how the specified words would be completed.
comopt
continueResume the next iteration of a for, while, select, or Until loop.
declareDeclare a variable or variable type.
you will sayDisplays a list of currently remembered directories.
disownDeletes the specified jobs from the jobs table for the process.
threw outDisplays the string specified in STDOUT.
enableEnables or disables the specified built-in shell command.
evalConcatenates the specified arguments into a single command and executes the command.
execReplaces the shell process with the specified command.
exitForces the shell to exit with the specified exit status.
exportSets the specified variables to be available to child shell processes.
fcSelect a list of commands from the history list.
fgResume a job in close-up mode.
getoptsParses the specified positional parameters.
hashFinds and remembers the full path of the specified command.
helpDisplays a help file.
historyShows command history.
ifUsed for branching.
jobsLists active jobs.
killSends a system signal to the specified process ID (PID).
letEvaluate each argument in a mathematical expression.
localCreate a limited scope variable in a function.
logoutExits a login shell.
mapfile
popdRemoves entries from the directory stack.
printfDisplays text using formatted strings.
pushdAdds a directory to the directory stack.
pwdDisplays the path name of the current working directory.
readReads a line of data from STDIN and assigns it to a variable.
readonlyReads a line of data from STDIN and assigns it to a variable that cannot be changed.
returnForces a function to exit with a value that can be retrieved by the calling script.
setSets and displays values ​​of environment variables and shell attributes.
shiftTurn the positional parameters down one position.
shoptToggles the values ​​of variables that control optional shell behavior.
sourceReads and executes commands from a designated file in the current shell.
suspendSuspends shell execution until a SIGCONT signal is received.
testReturns an exit status of 0 or 1 depending on the specified condition.
timesShows the accumulated system and user shell time.
trapExecutes the specified command if the specified system signal is received.
typeShows how the specified words would be interpreted if used as a command.
typesetDeclare a variable or variable type.
ulimitSets a limit on the specific resource for system users.
umaskSet default permissions for newly created files and directories.
unaliasDelete the specified alias.
one setDeletes the specified environment variable or shell attribute.
untilLoop that is very similar to the while loop except that it runs until the test command is executed successfully. As long as the test command fails, the until loop continues.
waitHave the shell wait for a job to finish.
whileWaits for the specified process to complete and returns the exit status.

Bash Symbols Overview

Here we have put together a collection of all the arcane syntax along with a brief description. Many of these symbols are repeated from before, but many are new; This is a good starting point if you are new to the language.

SYMBOLQUICK REFERENCE
#used for comments
$It is used for parameters and variables. It has a lot of edge cases.
()It is used to execute commands in a subshell.
psis used to save the output of commands that are sent to be executed in a subshell.
(( ))It is used for arithmetic.
$()is used to retrieve the output of arithmetic expressions, either for use with a command or to save the output to a variable.
$[ ]obsolete integer expansion construct replaced by $(( )). Evaluates whole numbers in square brackets
[ ]It is used for testing and is integrated. It is useful in some cases for file name expansion and string manipulation.
[[ ]]It is used for testing. This is the one you should use unless you can think of a reason not to.
<( )It is used for process replacement and is similar to a pipe. It can be used whenever a command expects a file and can use several at once.
{ }It is used for sequence expansion.
${ }It is used for variable interpolation and string manipulation.
|is a pipe used to chain commands.
<used to feed input to commands from a file
>is used to send results to a file and delete any previous content in that file.
 |logical or
&&logical and
used for option prefixes
used for long option prefixes
&used to submit a job to the background
<<WORD<<-WORDused for heredocs
<<‘WORD'<<-‘WORD’strings are used   here
<<<used to add output to a file.
>>Single quotes are used to preserve the literal value.
‘ ‘Double quotes are used to preserve the literal value of all characters except $, ` ` and
» «The backslash is used to escape otherwise interpreted symbols/characters that have a special meaning.
\used to separate the components of a file name
/similar to a NOP: a do-nothing operation. It is a built-in shell with a true exit status.
:Used to separate commands intended to be executed sequentially.
;It is used to link arithmetic operations. They are all evaluated but only the last one is returned.
,represents the current directory.
.represents the main directory.
..expands to the home directory.
~It is deprecated and should not be used. Read more in their respective section.
` `It is deprecated and should not be used. Read more in their respective section.

Flow control

The control flow structures in Bash are simple, although Bash is unforgiving if you get the syntax wrong.

See   examples  on how to use control flow in bash.

SYNTAX STRUCTUREKEY WORDS OR SYMBOLSDESCRIPTION
Ifyes then fiTest a condition.
If-elseyes then yes no fiTest a condition and use a fallback if the test fails.
if-elif-elseif then elif if not fiProvides additional tests and a fallback if all tests fail. You can omit the elif conditions or add as many intermediate conditions as you like. Similarly, you can skip the else resource.
Forto makeIterate over a sequence, a list or anything as far as the imagination goes.
Whilewhile doingAs long as a condition is true, repeat until that condition is no longer true.
Untiluntil it finishThe inverse of the while loop: as long as the test command fails, the until loop continues.
Selectselect what to doIt is used to easily generate menus. Any declaration inside can be another selection construct, thus allowing the creation of submenus.
casecase ) ;; that CAlternative if branch. Each case is an expression that matches a given pattern (that is, a case).

Frequent questions

What do $1 and $2 mean in Bash?

These would be “positional parameters” in a bash script. In this context, they would refer to the first and second arguments passed to the script. For example, if you wrote a script called “myTestScript.sh” with two arguments, such as:

./myTestScript.sh arg1 arg2

$1 would refer to the first argument and $2 would refer to the second.

What is $ in Bash?

$ represents a variable, which can be used to store values ​​such as numbers, strings, or arrays. You use $ to call that variable in a script. 

For example, if you set a variable like this: fav_color=blue

You can invoke it in a script with the line: echo “My favorite color is $fav_color” for the response “My favorite color is blue”

Is Bash easier than Python?

While the two languages ​​are similar in many ways, we would say that Bash would probably be easier to learn. 

We say this not because there is a steep learning curve for Python, as you can learn the basics of any of them in about the same amount of time. Python is simply capable of performing more complex operations, so as you progress in your learning, there is more to cover in Python.

How to run the Bash command in Windows Powershell?

To run Bash on a Windows system, you need to install the Windows Subsystem for Linux  . As described on the Microsoft website,

“The Windows Subsystem for Linux allows developers to run a GNU/Linux environment (including most tools, utilities, and command-line applications) directly on Windows, without modification, without the overhead of a traditional virtual machine or configuration. dual boot.  «

Conclusion

As we close this BASH Quick Guide, we’ve broken down the keys to optimizing the terminal experience. From customizing the interface to efficiently executing commands, these tips and tricks not only save time but also boost cybersecurity skills. The BASH terminal, when mastered, becomes a powerful tool for professionals looking to hone their art in digital defense.

We hope you found this cheat sheet helpful. The bash terminal is a powerful tool for automating tasks and managing settings. It’s useful for everyone from system administrators, developers, and cybersecurity personnel to the average user who chooses Linux as their daily driver.

We recommend that you take a look at our Chronological list of resources to learn Bash from complete beginner to advanced level to fully develop your knowledge base and get the most out of the command line.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *