0% found this document useful (0 votes)
1 views20 pages

4. Unit II Shell Scripting and Automation Basics (Using Git Bash)

This document provides an overview of shell scripting and automation basics using Git Bash, detailing learning outcomes, shell types, and their applications in task automation, system administration, and software development. It covers the structure of Git repositories, the functionality of Git Bash, and includes practical examples of writing scripts, using variables, and implementing conditionals and loops. The content aims to enhance productivity and efficiency in system administration through effective scripting techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views20 pages

4. Unit II Shell Scripting and Automation Basics (Using Git Bash)

This document provides an overview of shell scripting and automation basics using Git Bash, detailing learning outcomes, shell types, and their applications in task automation, system administration, and software development. It covers the structure of Git repositories, the functionality of Git Bash, and includes practical examples of writing scripts, using variables, and implementing conditionals and loops. The content aims to enhance productivity and efficiency in system administration through effective scripting techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Republic of the Philippines

BOHOL ISLAND STATE UNIVERSITY


Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

MODULE 4: Shell Scripting and Automation Basics (Using Git Bash)

I. Learning Outcomes
By the end of this session, students should be able to:
1. Understand the basics of shell scripting and its applications.
2. Learn to write simple scripts for task automation.
3. Develop skills to create scripts that enhance productivity in system administration.

II. Introduction to Shell Scripting Concepts


A shell script is a program written for the shell, or command line interpreter, of an
operating system. Shell scripts automate tasks and are typically used for system
administration purposes. They allow users to execute a sequence of commands in a
batch, improving efficiency for repetitive tasks.

Common Shell Types


• Bash (Bourne Again SHell)
Bash is the most widely used shell in Linux and macOS environments.
Developed by Brian Fox for the GNU Project, it was first released in 1989
as a free software replacement for the original Bourne Shell (sh).

Features:
• Supports scripting and command execution.
• Default shell for most Linux distributions.
• Allows for user configuration through .bashrc.
• Lacks inline wildcard expressions, which limits pattern searching
compared to some other shells.

• Sh (Bourne Shell)
The Bourne Shell is the original Unix shell, created by Stephen Bourne at
Bell Labs in the 1970s. It laid the groundwork for many modern shells.

Features:
• Simplicity and efficiency in command execution.
• Limited features compared to modern shells like Bash and Zsh.
• Primarily used for running shell scripts and simple command-line
tasks.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

• Zsh (Z Shell)
Zsh, developed by Paul Falstad in 1990, is an extension of the Bourne shell
that incorporates features from Bash, Korn Shell, and C Shell. It is known
for its enhanced interactive capabilities.

Features:
• Offers advanced tab completion and command history.
• Highly customizable with support for plugins and themes (e.g., Oh
My Zsh).
• Supports inline wildcard expressions, making it more flexible than
Bash

• Csh (C Shell)
Csh is a Unix shell with a syntax resembling the C programming language,
developed by Bill Joy in the late 1970s.

Features:
• Provides a C-like syntax that appeals to programmers familiar with
C.
• Includes features like job control and history substitution.
• Less commonly used today compared to Bash and Zsh.

Applications of Shell Scripting


• Task Automation
Shell scripting is an essential tool for automating repetitive tasks, which
helps in saving time and reducing human error. Common applications
include:
• Backups: Automate the process of backing up files and directories
at scheduled intervals, ensuring data integrity and availability.
• File Transfers: Use scripts to automate file transfers between
servers or local machines, incorporating tools like scp or ftp. This is
particularly useful for regularly scheduled data synchronization.
• System Monitoring: Automate the monitoring of system health,
performance metrics, or resource usage (CPU, memory, disk
space) by running scripts that log this information and alert
administrators of any anomalies.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

• System Administration
Shell scripts play a critical role in system administration by simplifying
complex tasks:
• User Management: Scripts can automate the creation, deletion,
and modification of user accounts using commands
like useradd, usermod, and userdel. This helps maintain consistent
user permissions and access controls across systems.
• File Permissions: Administrators can write scripts to manage file
permissions systematically using commands like chmod, chown,
and chgrp, ensuring that security policies are enforced consistently.
• Service Management: Automate the starting, stopping, or
restarting of services with commands such as systemctl or service,
facilitating easier management of system processes and daemons.

• Development and Deployment


In software development environments, shell scripting is invaluable for
streamlining workflows:
• Version Control: Automate interactions with version control
systems (like Git) to handle tasks such as committing changes,
merging branches, or deploying code. Shell scripts can encapsulate
these commands to reduce manual input errors.
• Continuous Integration: Scripts can facilitate the automation of
testing and building software applications as part of a continuous
integration pipeline. This includes running tests, compiling code,
and packaging applications for deployment.
• Deployment Processes: Automate the deployment of applications
across different environments (development, staging, production)
using scripts that handle configuration management and application
updates. This ensures consistency and reduces downtime during
updates.

Why Use Shell Scripting?


• Automation
Shell scripting allows users to automate routine tasks, reducing manual
effort. This is particularly useful for system maintenance, backups, and
repetitive file management tasks.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

• Efficiency
By automating processes, shell scripting increases productivity. Users can
execute complex commands or sequences of commands with a single
script rather than entering them manually each time.

• Flexibility
Shell scripts can handle a wide range of tasks:
• File Manipulation: Create, delete, or modify files and directories.
• Program Execution: Run applications or scripts automatically.
• Text Processing: Generate reports or format output easily.

III. Git and Repositories (Repo’s)


Git is a version control system that records changes to our files at any given time
Collaborate on projects and have local versions of the project on your computer Store
revisions of a project in just one directory
• Go back to a different version of the project
• Work on new features without messing up the main codebase

On the other hand, a Git repository (or repo) is a virtual storage space for your
project, allowing you to save and manage different versions of your code over time. It
enables developers to track changes, collaborate with others, and maintain the integrity
of their projects.

Types of Git Repositories


1. Local Repository:
• A local repository is stored on your personal computer. It allows you to work
independently without needing an internet connection.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

• You can initialize a local repository in any project folder using the command
git init

• This command creates a .git directory within your project, which contains
all the necessary files for version control.

2. Remote Repository:
• A remote repository is hosted on a server (like GitHub, Bitbucket, or GitLab)
and is accessible over the internet.
• Remote repositories facilitate collaboration among multiple developers,
allowing them to push and pull changes to and from the central repository.
• You can clone a remote repository to create a local copy using git clone
<repository-url>

Repository Structure
A typical Git repository contains several key components:
• .git Directory: This hidden directory stores all the metadata and object database
for your repository. It includes:
• Branches: References to commit objects representing different lines of
development.
• Tags: Markers for specific points in history (e.g., releases).
• Objects: The actual content of your files and directories at various points
in time.
• Configuration Files: Settings that define how Git behaves in that
repository.
• Working Directory: This is where you edit files. It reflects the current state of the
project based on the last commit.

IV. Git Bash and the Basics


Git Bash is a terminal emulator that provides a Unix-like shell environment for
Windows. It supports Git commands and Unix shell scripting, making it a powerful tool for
both version control and automation.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

In this section, you will learn how to write basic shell scripts using Git Bash. This
includes creating and running scripts, using variables, and incorporating basic logic (loops
and conditionals).

Common Command-Line-Interfaces
1. mkdir – Creates a new directory (folder) with the specified name.
Syntax: mkdir [directory-name]
Example:

This command creates a new directory named sample_dir in the


current directory.

2. rmdir – Removes an empty directory with the specified name.


Syntax: rmdir [directory-name]
Example:

This command deletes the directory named sample_dir, but only if


it is empty.

3. pws – Stands for Print/Present Working Directory, displays the current working
directory's full path.
Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

4. ls – lists all files and directories in the current directory.


Example:

5. cd – Stands for Change Directory, changes the current working directory to the
specified directory.
Syntax: cd [directory-name]
Example:

6. cd .. – Moves up one level in the directory structure.


Example:

7. touch – Creates a new, empty file with the specified name.


Syntax: touch [filename.extension]
Example:

This command creates a new empty file named sample_file.txt in


the current directory.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

8. rm – Removes the specified file.


Syntax: rm [filename.extension]
Example:

This command deletes the file named sample_file.txt.

Checking Versions and Configuring Git


1. git --version – Displays the currently installed version of Git.
Example:

2. git config --global user.name – Sets the username for all Git repositories on
your system.
Syntax: git config --global user.name [username]
Example:

3. git config --global user.email – Sets the email address for all Git repositories
on your system.
Syntax: git config --global user.email [email]
Example:

4. git config user.name – Displays the configured global username.


Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

5. git config user.email – Displays the configured global email.


Example:

V. Writing Simple Scripts for Task Automation


Automation is a powerful way to save time and reduce errors by automating
repetitive tasks. Bash scripting is a great tool for this, especially when combined with Git
commands. In this guide, we'll walk through creating simple scripts to automate common
Git tasks.

Writing Your First Shell Script in Git Bash


1. Create a New Script file

2. Add Shebang Line


Add a script at the first line of the shell script. It should be the shebang
#!/bin/bash, which tells the system that this script should be run with the Bash
shell.
Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

3. Write the script


Start by adding a simple command in the shell script.
Example:

4. Make the script executable


Save the script and make it executable.
Example:

5. Run the script


Run the script by providing a commit message as an argument.
Syntax: ./[shell_script_name].sh "[optional message]"
Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Using Variables in Git Bash Scripts


Variables in shell scripting are essential for storing data that can be referenced
and manipulated throughout the script. In Git Bash (as in any Bash shell), variables allow
scripts to be more flexible, dynamic, and powerful. This section will go into detail about
how to use variables in Git Bash, including their creation, usage, and some common
practices. In this guide, we’ll explore how to use variables in Git Bash scripts to automate
tasks and enhance functionality.

1. Creating Variables
Variables in Bash do not need a type declaration. Assign values to variables
using the = sign without spaces:
Syntax: [variable_name]="[value]"
Example:

2. Using Variables
To use a variable, prefix the variable name with a dollar sign ($):
Syntax: echo $[variable_name]
Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

3. Read User Input into a Variable


Use read to take input from the user and store it in a variable:
Syntax: read -p "[Input Message here]" [variable_name]
Example:

4. Arithmetic Operations in Variables


In Git Bash, you can perform arithmetic operations by using the $(()) syntax.
Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Using Conditionals and Loops in Git Bash


Conditionals and loops are essential control structures in shell scripting. They allow
scripts to make decisions (conditionals) and repeat tasks (loops). In Git Bash, conditionals
and loops are implemented using familiar Bash syntax. Understanding these structures
helps you write more powerful and flexible scripts, automating complex tasks efficiently.

Types of Conditional Statements in Git Bash


1. if, elif, else Statements
The if statement evaluates a condition, and if it’s true, the code block within
the statement is executed. You can extend this logic using elif (else if) for
additional conditions, and else to handle all other cases.
Syntax:
if [ condition ]; then
# commands to run if condition is true
elif [ another_condition ]; then
# commands to run if another condition is true
else
# commands to run if no condition is true
fi

Side Note:
▪ [ condition ]: The condition is placed inside square brackets
and can be an expression that returns true or false (e.g.,
comparing numbers, checking file existence, etc.).
▪ fi: This keyword marks the end of the if statement.

Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Comparison Operators in Conditionals


You can use various comparison operators in conditionals to compare
numbers, strings, or file attributes. Here are some common ones:
• String Comparison:
o [ "$var" = "$value" ] : True if var is equal to value.
o [ "$var" != "$value" ] : True if var is not equal to value.

• Numeric Comparison:
o [ "$num1" -eq "$num2" ] : True if num1 is equal to num2.
o [ "$num1" -ne "$num2" ] : True if num1 is not equal to num2.
o [ "$num1" -gt "$num2" ] : True if num1 is greater than num2.

• File Conditions:
o [ -f "$file" ] : True if the file exists and is a regular file.
o [ -d "$dir" ] : True if the directory exists.

Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

2. case Statements
A case statement is a cleaner alternative to multiple elif statements, especially
when you're checking a variable against many different values.
Syntax:
case $variable in
pattern1)
# commands for pattern1
;;
pattern2)
# commands for pattern2
;;
*)
# commands for default case
;;
esac

Example:
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Types of Loops
1. for Loops
A for loop iterates over a list of items (such as files, numbers, or strings),
executing a block of code for each item.
Syntax:
for item in list; do
# commands to run for each item
Done

Side note:
▪ list can be a sequence of values, a list of files, or even the
output of a command.

Example:

2. while Loops
A while loop repeatedly executes a block of code as long as the given
condition is true.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Syntax:
while [ condition ]; do
# commands to run while condition is true
done

Example:

3. until Loops
An until loop is the opposite of a while loop: it runs until a condition becomes
true.
Syntax:
until [ condition ]; do
# commands to run until condition is true
Done
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Example:

VI. Git’s 3-Stage Architecture


When working with shell scripts in Git, understanding Git’s 3-stage architecture
helps ensure that you can efficiently track, manage, and version your script changes. Git
provides a structured way to handle changes in your code, moving them through different
stages before committing them to the project history. This architecture is essential for
automating tasks through shell scripting, as it keeps your changes organized and
manageable.

Overview of Git’s 3-Stage Architecture


Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Git’s version control system works on three key stages for managing files:
1. Working Directory
The working directory is where all the active changes in your files are made.
When you edit a shell script or create a new one, the changes first appear
here. These changes are either untracked (new files) or modified (existing files
that have been changed).

Checking the Status


To see what changes have been made in the working directory, use git status.

This command shows files that have been added, modified, or deleted but are
not yet staged for the next commit.

2. Staging Area
The staging area is where you prepare changes before committing them to the
repository. You must explicitly add your file changes from the working directory
to the staging area using the git add command. This stage allows you to
decide which files and changes are ready for the next commit.

Adding Files to the Staging Area


• git add . – Add all changes in the directory

• git add [file_name] – Add a specific file

Running git add moves the files from the working directory to the staging area.
Republic of the Philippines
BOHOL ISLAND STATE UNIVERSITY
Magsija, Balilihan, 6342, Bohol, Philippines
Office of Instruction
Balance I Integrity I Stewardship I Uprightness

System Administration and Maintenance

Now these changes are staged, meaning they are ready to be committed but
not yet saved to the repository.

3. Commit Stage
The repository is where the changes you have staged are committed.
Committing is the process of saving your staged changes into Git’s version
history. Once committed, these changes are part of your project’s history and
can be viewed, modified, or reverted.

Committing Changes
To save your staged changes to the repository, use git commit.

This records the changes in the repository, along with a message that
describes what the commit contains.

Viewing Commit History


You can view the history of commits to track your project’s progress using:

For a more simplified view, try:

This shows each commit in a compact format, displaying commit IDs and
messages in one line.

VII. Assessment Tasks


o Assignment
o Activity

You might also like