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 |
---|---|
-and | The file exists |
-to | The file exists (identical to -e but is obsolete and out of date) |
-F | The file is a normal file (not a directory or device file) |
-s | the file is not of zero size |
-d | the file is a directory |
-b | The file is a block device. |
-C | The file is a character device. |
-p | the file is a pipe |
-h | The file is a symbolic link. |
-l | The file is a symbolic link. |
-S | the file is a socket |
-t | the 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 |
-r | The file has read permission (for the user running the test). |
-w | the file has write permission (for the user running the test) |
-X | the file has execute permission (for the user running the test) |
-g | set-group-id (sgid) flag set on a file or directory |
-or | set-user-id (suid) flag set in file. |
-k | adhesive tip set. |
-EITHER | you own the file |
-G | File group ID same as yours |
-N | file modified since last read |
f1 -nt f2 | file f1 is newer than f2 |
f1 -ot f2 | file f1 is older than f2 |
f1-ef f2 | The 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.
FLAG | DESCRIPTION |
---|---|
-eq | is equal to |
-ne | is not equal to |
-gt | is greater than |
-ge | is greater than or equal to |
-lt | is less than |
-you | es 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.
FLAG | DESCRIPTION |
---|---|
= | is equal to |
== | is equal to |
!= | is not equal to |
< | is greater than ASCII alphabetical order |
> | is greater than ASCII alphabetical order |
-z | the string is null (i.e. of length zero) |
-north | the 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>].
FLAG | DESCRIPTION |
---|---|
-to | logical and |
-either | logical or |
Job identifiers
Job control allows you to selectively stop (suspend) the execution of processes and continue their execution at a later time.
NOTATION | DESCRIPTION |
---|---|
%N | Job number [N] |
%S | The invocation (command line) of the job starts with the string S |
%?S | Invocation (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 |
---|---|
1 | Catchall for general errors |
2 | Misuse of built-in shell functions |
126 | El comando invocado no puede ejecutarse |
127 | Command not found |
128 | Invalid argument to exit |
128+n | Fatal error signal “n” |
130 | Script finished by Control-C |
Signs
UNIX V system signs.
NAME | NUMBER | ACTION | DESCRIPTION |
---|---|---|---|
SIGHUP | 1 | exit | Hanging |
SIGINT | 2 | exit | Interrupts. |
SIGQUIT | 3 | memory dump | In peace. |
SIGILL | 4 | memory dump | Illegal instruction. |
SIGTRAP | 5 | memory dump | Trail trap. |
SIGIOT | 6 | memory dump | IOT instruction. |
SIGEMT | 7 | memory dump | MT Instruction. |
SIGFPE | 8 | memory dump | Floating point exception. |
SIGKILL | 9 | exit | Deaths (cannot be caught or ignored). |
SIGBUS | 10 | core dump | Bus error. |
SIGSEGV | eleven | core dump | Segmentation violation. |
SIGSYS | 12 | core dump | Bad argument for the system call. |
SIGPIPE | 13 | exit | He writes on a pipe without anyone being able to read it. |
SIGALRM | 14 | exit | Alarm clock. |
SIGTERM | fifteen | exit | Software termination signal. |
Sending control signals
You can use these key combinations to send signals.
KEY COMBINATION | DESCRIPTION |
---|---|
Ctrl+C | The interrupt signal sends SIGINT to the job running in the foreground. |
Ctrl+Y | The 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+Z | The 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 |
d | directory |
I | Link (symbolic) |
c | Character device |
yes | Plug |
p | Named Pipe |
b | bloqueo ofdispositivo |
Permissions
Now you can tell what that arcane-looking string rwxrwxrwx is when you invoke ls -l
CODE | DESCRIPTION |
---|---|
yes | setuid when in user column |
yes | setgid when in group column |
t | sticky bit |
0—— | The right of access that this place should have is not granted. |
4—–r | Read access is granted to the user category defined here. |
2—–w | Write permission is granted to the user category defined here. |
1—–x | The execute permission is granted to the user category defined here. |
or | User permits |
g | group permissions |
oh | other permissions |
Special files
Files that are read by the shell. Listed in order of execution.
ARCHIVE | INFORMATION |
---|---|
/etc/profile | Launched automatically on login |
~.bash_profile ——————— ~/.bash_login ——————— ~.profile | Whichever is found first is executed at login. |
~/.bashrc | It 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
PATTERN | DESCRIPTION |
---|---|
${#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” $substring | Numeric 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 $length | Extract $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 newline | word 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.
DOMAIN | DESCRIPTION |
---|---|
$0 | Name of the script itself. |
$1…$9 | Parameter 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. |
!n | Refers to the <n>-th command line. |
!-n | Refers to the current command line minus <n>. |
!string | Refers 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.
Symbol | DESCRIPTION |
---|---|
* | 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
OPERATOR | EFFECT |
---|---|
. | 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 CLASS | EQUIVALENT | EXPLANATION |
---|---|---|
[: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.
BUILTIN | DESCRIPTION |
: | 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 ]. |
alias | Defines an alias for the specified command. |
b.g. | Resume a job in background mode. |
bind | Binds a keyboard sequence to a read line function or macro. |
break | Exits a for, while, select, or Until loop. |
built in | Runs the built-in command for the specified shell. |
caller | Returns the context of any active subroutine calls. |
case | |
CD | Changes the current directory to the specified directory. |
command | Executes the specified command without the normal shell search. |
compgen | Generates possible ending matches for the specified word. |
complete | Shows how the specified words would be completed. |
comopt | |
continue | Resume the next iteration of a for, while, select, or Until loop. |
declare | Declare a variable or variable type. |
you will say | Displays a list of currently remembered directories. |
disown | Deletes the specified jobs from the jobs table for the process. |
threw out | Displays the string specified in STDOUT. |
enable | Enables or disables the specified built-in shell command. |
eval | Concatenates the specified arguments into a single command and executes the command. |
exec | Replaces the shell process with the specified command. |
exit | Forces the shell to exit with the specified exit status. |
export | Sets the specified variables to be available to child shell processes. |
fc | Select a list of commands from the history list. |
fg | Resume a job in close-up mode. |
getopts | Parses the specified positional parameters. |
hash | Finds and remembers the full path of the specified command. |
help | Displays a help file. |
history | Shows command history. |
if | Used for branching. |
jobs | Lists active jobs. |
kill | Sends a system signal to the specified process ID (PID). |
let | Evaluate each argument in a mathematical expression. |
local | Create a limited scope variable in a function. |
logout | Exits a login shell. |
mapfile | |
popd | Removes entries from the directory stack. |
printf | Displays text using formatted strings. |
pushd | Adds a directory to the directory stack. |
pwd | Displays the path name of the current working directory. |
read | Reads a line of data from STDIN and assigns it to a variable. |
readonly | Reads a line of data from STDIN and assigns it to a variable that cannot be changed. |
return | Forces a function to exit with a value that can be retrieved by the calling script. |
set | Sets and displays values of environment variables and shell attributes. |
shift | Turn the positional parameters down one position. |
shopt | Toggles the values of variables that control optional shell behavior. |
source | Reads and executes commands from a designated file in the current shell. |
suspend | Suspends shell execution until a SIGCONT signal is received. |
test | Returns an exit status of 0 or 1 depending on the specified condition. |
times | Shows the accumulated system and user shell time. |
trap | Executes the specified command if the specified system signal is received. |
type | Shows how the specified words would be interpreted if used as a command. |
typeset | Declare a variable or variable type. |
ulimit | Sets a limit on the specific resource for system users. |
umask | Set default permissions for newly created files and directories. |
unalias | Delete the specified alias. |
one set | Deletes the specified environment variable or shell attribute. |
until | Loop 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. |
wait | Have the shell wait for a job to finish. |
while | Waits 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.
SYMBOL | QUICK 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. |
ps | is 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<<-WORD | used 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 STRUCTURE | KEY WORDS OR SYMBOLS | DESCRIPTION |
---|---|---|
If | yes then fi | Test a condition. |
If-else | yes then yes no fi | Test a condition and use a fallback if the test fails. |
if-elif-else | if then elif if not fi | Provides 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. |
For | to make | Iterate over a sequence, a list or anything as far as the imagination goes. |
While | while doing | As long as a condition is true, repeat until that condition is no longer true. |
Until | until it finish | The inverse of the while loop: as long as the test command fails, the until loop continues. |
Select | select what to do | It is used to easily generate menus. Any declaration inside can be another selection construct, thus allowing the creation of submenus. |
case | case ) ;; that C | Alternative 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.