- Understand loops, variables, conditionals, functions
- Create a portfolio project
- Write a blog article about what you learned
Used for specifying the interpreter for executing a shell script. By including this shebang at the beginning of a shell script, you ensure that the script is executed correctly with the appropriate interpreter. It tells the operating system which program should interpret and execute the commands in the script
#!/bin/bashWhile Loops:
while [ <test>]
do
<command>
doneFor Loop:
this is more akin to a forEach() loop in JS since the loop number is automatically set by
for var in <$list>
do
<commands>
doneRanges:
More akin to the vanilla for loop in JS
for value in {1..5}
do
echo $value
doneTwo actions performed for variables:
- Setting value for variables
- Reading value of variables
Setting Variables:
variable="test"Reading Variables:
echo $variableLocal Variables:
local variables are variables that are defined and accessible only within the scope of a specific function.
Setting Local Variables:
calculate_sum() {
local a=5
local b=10
local sum=$((a + b))
echo "The sum is: $sum"
}Conditional operators:
| Operator | Description |
|---|---|
| -eq | Returns true if two numbers are equivalent |
| -lt | Returns true if a number is less than another number |
| -gt | Returns true if a number is greater than another number |
| == | Returns true if two strings are equivalent |
| ≠ | Returns true if two strings are not equivalent |
| ! | Returns true if the expression is false |
If Statement:
if [ conditional ]; then
<command>
fiIf-else Statement:
if [ conditional ]; then
<command>
else
<command>
fiIf-elif-else Statement:
if [ conditional ]; then
<command>
elif [ conditional ]; then
<command>
else
<command>
fiThere are two ways to declare functions in bash:
- First way to Declare a Function:
function_name() {
<commands>
}- Second way to Declare a Function:
function function_name() {
<commands>
}Single-line Function:
function_name() { <commands>; }
# in single line, requires semi-colon after last commandPassing arguments:
add_numbers() {
a="$1"
b="$2"
c=$(($1 + $2))
echo -e "${GREEN}The sum of $a and $b is $c${NC}"
}
# notice how args are passed
add_numbers 4 6Return Values:
Unlike in other programming languages, Bash functions don’t allow you to return a value when called. When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure.`
The return status can be specified by using the return keyword, and it is assigned to the variable $?. The return statement terminates the function. You can think of it like the function’s exit status.
returnis used to exit a function and provide a value back to the caller, whileexitis used to terminate the entire script or shell session.
Success Return:
# success
success_function() {
return 0
}
success_function
echo -e "?$"Failure Return: