Skip to content

Instantly share code, notes, and snippets.

@OffXec
Created March 6, 2021 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OffXec/a69e51f6b57e29292fe4829f15bc3285 to your computer and use it in GitHub Desktop.
Save OffXec/a69e51f6b57e29292fe4829f15bc3285 to your computer and use it in GitHub Desktop.
"Learning Bash Scripting" course notes.
Notes I've taken from when I took the "Learning Bash Scripting" course on LinkedIn Learning.
Figured I'd share :)
--------------------------------------------
-"Learning Bash Scripting"-
Course Link:
https://www.linkedin.com/learning/learning-bash-scripting-2
--------------------------------------------
Self-Promo:
[https://www.linkedin.com/in/offxec/]
--------------------------------------------
#BASH NOTES.
shebang line: !#/usr/bin/env bash
BASH = BOURNE AGAIN SHELL
chsh - change SHELL
---------------
piping takes result of one process and sends it to anothrer.
example: cat file | piping
redirect standard output: ls /notreal 1> output.txt
redirect standard error: ls /notreal 2> error.txt
input redirection: cat < list.txt
append to docunment:
error document: cat << EndOfText
>EndOfText
---------------------
echo - ends line with new line.
printf - no new line at end.
---
command echo
builtin echo
---
command -V program_name (checks for builtin)
enable -n bultin_name (enabled command version instead of builtin)
enable -n > list all enabled commands
help - list helps for all builtin commands.
-----
Parentheses - used for enclosing conditions & function parametrers.
Braces - function bodies and objects
Brackets - used for lists or array notaions.
(In BASH these can act as commands themselves.)
-------------
BASH Expressions & Substitutions:
~ - Tilde expansion
(repersents the val of home directory)
---------------
{...} - Brace expansion
(Substitues in itmes from a list of values,
separated by commas or range of numbers or letters in any given pattern separated by two periods or dots. )
(example: echo {1..10} - echos pattern inside braces.)
(echo {cat,dog,fox})
-----------------
${...} - Parametrer expansion - allows us to recall stored values and transform them in various way.
(a="value"
echo ${a} or $a)
${a/replace letter//replace with}
{echo ${a:postional start value:end value}}
$(...) - Command Substitution - Allows us to use the output of a command within another command
example: echo "kernel is $(uname -r)"
$((...)) - Arithmetic expansion - perform math and uses the results inside a print statement.
$((number + number)), etc.
---------------------------------------------
Nano -
Open file: nano filename
Save file: CTRL+O
Exit: CTRL+X
--------------
oneliners - a command or series of commands presented as one line of text.
example: cmd;cmd;cmd - cmd | cmd | cmd | cmd.
-------------
\escaping character\
-------------
'' - prints everything as is
"" - normal print.
----------
echo -n > turns off new line.
(echo -n "this";echo -n "and that")
---------
Variables: (NO SPACES & CASE SENSTIVE)
example: variablename=here.
--
read-only variable(cannot be changed):
declare -r variable="name" - read only.
declare -l var="name" - turns whatver it gets to all lowercase
declare -u uppercase="name" - turns whatever it gets to all UPPERCASE.
declare -i varnum=3> sets variable as integer.
decalre -p > show all variable declared in the current session.
declare -a name=("items" "go" "here")
declare -A array_name
env - shows all enviourment variables:
$USER - gets user name
----------
MATH:
Addition: +
Subtraction: -
Multiply: *
Divide: /
Modulo - % - gives remainder of a division operation.
Exponentation: ** -
--
Incrementation:
[Arithmitic evaluations] - provides exit status.
((a++)) - adds 1 to the variable
((a--)) - takes 1 away from variable
---
BC - Basic Calculator: scale=return
$RANDOM - 0 - 32,767.
---
Test & Compare: returns in 0 or 1. (True or False.)
0 - suceess
1- error.
---
[...] - compare and test values: builtin "test"
[[...]] - extended test.
-d - test if directory exist.
-z - test if item exsist.
$? - reads the value of a returned status
-eq - equal
-ne - not equal
-gt - greather than
-lt - less than
-ge - greater than or equal to.
-le - less than or equal to.
-e - interpets escaped characters like \t \n \a, and allows us to use colored output.
! - gives opposite of the truth value
&&(AND) - says true when both are true on each side.
||(OR) - One or the other needs to be true to return true
===============================
Text Colors:
--003[**m
----------
30 - black, 31 -Red, 32 - Green, 33- Yellow, 34- Blue
35-Pink, 36-Cyan, 37- White.
--
Background Colors:
40 - Black, 41 - Red, 42 - Green, 43- Yellow, 44- Blue,
45 - Pink, 46- Cyan, 47- White.
--
Bright Text Colors:
90 - Black, 91- Red, 92- Green, 93- Yellow, 94- Blue,
95- Pink, 96- Cyan, 97- White.
----
Bright BackGround:
100- Black, 101- Red, 102- Green, 103- Yellow, 104- Blue,
105- Pink, 106- Cyan, 107- White.
----
Output Styles:
0 - Resets
1 - Bright
2 - Dim
4 - Underline
5 - Blinking
6 - Inverted
7 - Strikethrough
"\033[1COLOR;COLOR\033[0m"
----
FONTCOLOR;BACKCOLOR
m- ends expression
0m - resets colors.
------
Usage:
red="\033[31;40m"
none="\033[0m"
echo -e $red"TEXT"$none" TEXT"$none
==================================================
PRINTF:
- allows you to use a placeholder to replace variable and expressions.
- No new line, so need to use \n"
- %s - string placeholder
- %d - number placeholder.
"-" - Left Alignment.(%-d)
example:- printf "Text is %s and %s\n" $variable $(variable)
============================================
ARRAYS: Indexed & Associated.
*0 based notation*
*Both limited to one level or layer*
--
indexed: name=("item" "item" "item")
Locating item: array_name[index #]
Add(append) to array: array_name+=("name")
Set item by index: array_name[index]="new name"
List all values: array_name[@](echo ${array_name[0]})
----------
Associate Arrays: Specify a key and a value.
declare -A array_here
array_here["item1"]="name"
array_here["job"]="what"
Accessing Keys: array_here["key_name"] - echo ${array_here["key_name"]}
################
CONTROL STRUCTURES:
**IF STATEMENT: executes code bassed on a conditonal expression.
**EXAMPLES:
if [[condition]]/(COMMAND HERE); then
CODE IS TRUE PRINT
elif [[ CONDITION]]; then
CODE HERE FOR ELSEIF
else
CODE HERE
fi
--
**LOOPS:
- For, While & Until Loops.
-- For loops iterates through a list of items, running code for each item.
-- While Loops run while a condition IS TRUE.
-- Until loops run until a condition BECOMES TRUE
-- SLEEP #: Pauses loop for [x] amount of milliseconds/seconds.
**EXAMPLES:
while [[ CONDITION IS TRUE]]
do
CODE HERE
done
****UNTIL LOOP:
until [[EXPRESSION BECOMES TRUE]]
do
CODE HERE
done
****FOR LOOP
for VARIABLE in STRING/ARRAY
do
CODE WITH $VARIABLE
done
(one liner: for var in condition; do $var; done)
(ex 2:
for ((variable=1; condition; variable++ ))
do
echo $variable
done
*****CASE STATEMENTS:
-- Checks an input against a set of predefined values
-- Runs code when an input matches a conditon.
****EXAMPLE:
$thevar="something"
case $thevar in
condition) echo, etc here.;;
conditon 2|condition3) output here;;
*) - No match found in case.
esac
#################################################
--FUNCTIONS--: Allows us to to repeatedly call a piece of code.
$0 - script name
$1 - first argument passed to the function
$2 - second passed
$3 - third passed, etc
$@ - represents the list of arguments given to a function
$FUNCNAME - represents the name of the function.
Local variables are only accessible inside the functions.
local variable_name="name"
------------------
function name {
CODE HERE
}
---------
funct_name(){
CODE HERE $1
}
funct_name argument
##################################
***READING AND WRITING TEXT FILES***
--- "STRING" > out.txt (overwrites the contents of the txt)
--- "STRING" >> out.txt (appends to the end of the text)
EXAMPLE: while read l; do echo $l done < my.txt
#################################
ARGUMENTS:
-- Allows us to pass information into a script from the CLI.
-- Text that represents a string, filename, etc.
-- Repersented by numbered variables($1, $2, etc)
------------------
***OPTIONS:
-- Allow us to pass information into a script
-- Are a combination of a dash and a letter(-u or -p, etc)
-- getopts - to access options.
--- :letter -> says if it tries an option not set in the script.
--- letter: -> opening and closing colons means it expects an argument
--- letter -> if the flag was used or not, outputs predefined argument.
*************EXAMPLE:
while getopts letter:letter: option; do
case $option in
letter) command=$OPTARG;;
?) echo "unknown command!"
esac
done
------
while getopts letter option; do
case $option in
letter) echo, etc;;
esac
done
-- ./script -letter argument -letter argument
################################
Gathering Input - Interactively.
READ - Keyword that allows us to gather input,
pausing the script until input is provided.
-- input is stored inside a variable
-s -> tells input to be silent, no typing symbols.
-p -> writes out a prompt and a response area on the same line.
-e -> allows us to use the read interpreter, and editing buffer.
-i -> when left blank, the value becomes pre-determined.
example:
read variable_name
#################################
menu style:
select in menu_item in "menu" "menu"
do
case $menu_item in
menu1) menu stuff;;
menu2) menu stuff;;
quit) break;;
*) unknown command.
esac
done
####################################
TROUBLE SHOOTING:
! -a $(which tool_name) && echo "cannot find"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment