Bash For TT
Bash For TT
Bash, short for "Bourne Again Shell," is a powerful and widely used command-
line interpreter for Unix and Unix-like operating systems. It's the default shell
for most Linux distributions and macOS. As a shell, it acts as a command
processor that allows users to interact with the operating system through text-
based commands.
Features of Bash:
1. Command Execution: Bash allows users to execute commands, launch
programs, and perform various operations through a command-line
interface.
2. Scripting: It supports scripting, enabling the creation of shell scripts
containing sequences of commands that can be executed automatically.
3. Variables: Bash allows the use of variables to store data and use it
throughout scripts or commands.
4. Control Structures: It provides control structures such as loops,
conditional statements, functions, and more, allowing for more complex
scripting and automation.
5. Redirection and Piping: Bash supports input/output redirection,
allowing the output of one command to be passed as input to another
command.
6. Wildcards and Globbing: Bash supports wildcards and globbing,
enabling the use of patterns to match filenames or strings.
7. Job Control: It provides functionalities for managing and controlling
multiple processes or jobs.
Basic Syntax: command [options] [arguments]
Key Components:
1. Commands: Commands are actions or operations you want to perform.
For example, ls to list files, mkdir to create a directory, echo to print
something on the screen, etc.
2. Options: Options modify the behavior of commands. They are usually
preceded by a hyphen (-) or double hyphen (--). For instance, in ls -l, -l is
an option to list files in long format.
3. Arguments: Arguments are additional information passed to commands
to act upon. For example, mkdir my_folder where my_folder is the
argument passed to the mkdir command.
4. Variables: Bash allows the use of variables to store and manipulate
data. Variables are defined as variable_name=value.
Scripting:
Bash scripting involves writing a sequence of commands that are stored in a
file and executed as a program. The script file usually starts with a shebang
line that tells the system which interpreter to use: #!/bin/bash that is to execute
the command via bash shell
Redirection and Piping:
Bash allows redirecting the output of a command to a file or another command
using redirection operators (>, >>, <). For example:
ls > files.txt This command redirects the output of ls to a file named files.txt,
overwriting its content if it already exists.
ls >> files.txt. This command appends the output of ls to a file named
filex.txt.
done < input.txt syntax is redirecting the input of the loop to read from the
file input.txt.
Piping (|) is used to pass the output of one command as input to another
command. For example: ls | grep ".txt". This command uses ls to list files
and passes the output to grep to filter only the files with .txt extension.
Job Control:
Bash allows job control functionalities, like running processes in the
background, switching between foreground and background jobs, suspending
jobs, etc., using commands like &, fg, bg, Ctrl + Z, jobs, etc.
Bash is an incredibly versatile and powerful tool, allowing users to efficiently
interact with the operating system and automate various tasks through both
interactive command execution and scripting capabilities.
VARIABLES
In the context of the Bash shell scripting language, variables are used to store
and manipulate data. Here's an in-depth look at variables in Bash:
Variable Naming Conventions:
Variable names are case-sensitive.
Can include letters, numbers, and underscores.
Must start with a letter or an underscore.
Should not start with a number.
Avoid using special characters in variable names.
Variable Declaration and Assignment
Variables are declared and assigned values using the following syntax:
variable_name=value. For example:
name=”John”
age=25
echo $name $age
This command will print "John 25" to the console, with a space between the
values stored in the name and age variables.
If you want a specific text format or to denote the values more explicitly, you
can use strings in the echo command:
name="John"
age=25
echo "Name: $name, Age: $age"
Let’s take a look at another example:
#!/bin/bash
# Set variables
name=”John”
age=30
city=”New York”
In bash we have:
environmental variables also known as system variables and;
declared variables also known as custom variables
variables on your system is known as environmental variables.
A variable that you define based on your specific needs or requirements within
your script or program custom variable.
To see the list of the environment variables on your system type: ENV.
To get the environment variables but limit it to users you filter using env |
grep user.
To get only the environment variable name: env | cut -d= f1
Rules and Best Practices for Variables in Bash:
1. Variable Expansion: Accessing the value of a variable is called variable
expansion. It's done by preceding the variable name with the dollar sign
($). For example: echo $name will display the value stored in the name
variable.
2. Double Quotes vs. Single Quotes: Using double quotes (" ") around
variables is advisable when you want to preserve whitespace and handle
special characters within the value. Single quotes (' ') treat everything as
literal, not expanding variables.
E.g greeting="Hello, World!" echo "$greeting" # This will print: Hello,
World!
echo '$greeting' # This will print: $greeting
In Bash, when you want to access or retrieve the data stored in a variable, you
use the dollar sign ($) followed by the variable name.
For instance, if you have a variable named name that contains the value
"John," to retrieve or use the value stored in the name variable, you'd use
$name in your script.
CONDITIONALS IN BASH SCRIPT
Conditional statements in Bash allow you to make decisions in your scripts
based on conditions. The primary conditional statements in Bash are if, else,
and elif (short for "else if").
IF conditional statement is used to make decisions if the condition is TRUE.
While ELSE is used to make or execute a decision if the conditions is false. In
conditionals when you want to start a script you use “if” then end with
inverted if which is “fi”.
Also when using we make use of what is called comparison operators or
equality checks. Common operators helps create conditions for if and elif
statements in bash. The equality checks are:
-eq is used for numbers means equals to. It works with numbers not
string;
-gt means greater than it works with numbers alone;
-lt means less than works with numbers;
-ne is not equal to works with numbers or strings;
! is negation.
We use [ ] to denote the conditional expression.
The [ ] is used to read input from the user and store in a variable
To check a file exists in bash use: -f.
To check a directory exists in bash use: -d.
Example: To create a file
#!/bin/bash
if [ -f “images.png” ]
then
echo “The images folder exists already moving on ...”
sleep 0.5
else
touch “images.png”
fi
In this example we are creating a file but we are first checking if a file exists
before creating and if it doesn’t it should create it after all. The sapce in the
square bracket is important to separate the square bracket from the test
expression inside them. Without the space, Bash will not recognize the square
brackets as part of the syntax for conditions. Also it makes the code more
readable and helps avoid parsing error.
Another example:
age=18
if [ $age -ge 18 ];
then
echo “You are an adult”
else
echo “You are not an adult yet”
fi
More examples:
# Get the current working directory
cwd=$(pwd)
echo $cwd
if [ -f "$cwd/images.png" ]
then
echo "the image file exist check again ..."
else
touch "images.png"
fi
#!/bin/bash
cd ~
if [ -f "images.png" ]; then
echo "The images.png file already exists ..."
sleep 0.5
else
touch "images.png"
echo "The images.png file has been created."
fi
Example 2
#!/bin/bash
age=12
if [ $age -eq 12 ]
then
echo "Positive"
else
echo "This is the wrong user"
fi
what if I put another conditionals like this
#!/bin/bash
age=12
if [ $age == "James" ]
then
echo "Positive"
else
echo "This is the wrong user"
fi
What should be the result? Find out yourself.
ASSIGNMENT
Write a Bash Script that checks the user’s age and displays a message based
on the age group.
INSTRUCTIONS
Ask the user to enter the age
Use conditionals to categorize the age into three groups: child (0-12),
teenager (13-19), and adult (20 and above)
Display a message based on the age group entered by the user.
If the user enters 10 the script should display “You are child”
If the user enters 16, it should display “You are a teenager” and the same
pply for adults.
LOOPS IN BASH
In Bash Scripting, loops allows you to execute a set of commands repeatedly
until the command is carried out completely.
There are 2 types of loops in bash:
For loop: Goes through a set of items, elements or range of value.
While loop continues to run a particular condition until the condition has
changed. It executes a set of commands as long as a condition is TRUE.
EXAMPLES
#!/bin/bash
while [ $num -lt 20 ] # Sets the condition for the loop. It continues as
long as the value of $num is less than 20
do
echo $num # prints the current value of num
num=$(( $num + 1 )) # increments the value of num by 1 in each
iteration
sleep 0.5 # pauses the execution for half a second; creating a
delay between each printed number
done
There are 2 types of command in loop:
Test command uses: [ ]
Read command uses: while read -r line
In bash < is how we read into a file.
EXAMPLE
counter=0
while [ $counter -lt 5 ]
do
echo "Counter: $counter"
((counter++))
done
To loop through the users array using FOR loop:
users=(“Junior” “John”)
for user in “${users[@]}”
do
echo $user
done
Another example:
#!/bin/bash
figure=i
for i in {1..5}
do
echo "Number: $i"
done
In bash Loops and Arrays makes use of the “cut” command.
The cut command in Bash is used to extract specific (columns) from each line
of a file or form piped input. It is particularly used when working with text-
based data like txt file or CSV (Comma Separated Value) file where
columns are separated by a specific character.
The cut command is: cut option with -d: -f. The colon there means it is a
delimiter. A delimiter in Bash is a character or a sequence of charactres that
divided different parts of data. It is commonly used to structure or organize
text-based data into distinct sections or fields.
EXAMPLE
myname="james:password=password1"
echo "$username:$password"
done < "$file"
The “line” there is a variable
This is how it is done.
Also remember that when you create and inventory file there must be an
empty space so that when the loops reads through the file the output will be
printed fully. Like The picture below.
The result will be this
ASSIGNMENT
Create and inventory file that contains this:
Then wirte a loop in Bash that will fetch only the users and password.
Loops control statements
‘break’: terminates the loop.
‘continue’: skips the current iteration and moves to the next one.
‘return’: exits the loop and script if used in a function.
‘exit:’ exits the loop and the entire script.
ARRAYS
If you want to map multiple items to the same variable, you use an array.
An Array is a collection of items that are usually similar. In Array the data
structure allows you to put items together/ or hold more than one items.
Usually the items are of similar types (numbers and numbers; strings and
strings).
E.g users=(“Jame” “John”). Anytime you put apostrophe “” around anything
it becomes a string.
In programming language, data flows from right to left. So that means that
whatever you’re storing will be from the right, where it’s being stored is on the
left hand side.
There are 2 types of arrays:
Indexed arrays or simple arrays
Associative arrays or complex arrays or maps
In indexed arrays you use indices/indexes to identify the items that are inside
the array.
To state you are using indexed arrays you use declare -a then <the array
variable>
In the shot James as an index of 0 and John has an index of 1 and so on.
Associative arrays also known as “Dictionaries” is a type of array in bash that
allows you to associate a key with a value.
To state you are using Associative arrays you use declare -A then <the array
variable>
Examples:
#!/bin/bash
users=("James" "John" "Jerry") # This is you array. The variable for
your could be anything.
The first thing you need to know is declaring an array in bash:
declare -a users ## This is used to declare an array in bash
Next is to know how to get the length of an array using:
# This is to get the length of an array
echo "${#users[@]}"
The output is:
The second task is to get an item alone in an array by using: echo "$
{users[2]}”
To get the last item of an array it will always have an index of the length of that
array -1
echo "${users[${#users[@]} - 1]}"
## To get the index of the last item of an array: echo $(( $
{#users[@]} - 1 ))
##
To
users+=("${new_users[@]}")
echo "${users[@]}"
unset users[0]
echo "${users[@]}"