NSCS-SYST1 Course - Chapter 8
NSCS-SYST1 Course - Chapter 8
I 1st Year Basic Training in Cyber Security ( 1BT ) 2024 / 2025 © Dr. Sassi BENTRAD - 2024
Basic Training in Cyber Security (1BT)
Formation de Base en Cyber-Sécurité (1FB)
CHAPTER
8
BASH PROGRAMMING AND SHELL SCRIPTING
SYST1’2024/2025
MODULE DESCRIPTION SHEET : INTRODUCTION TO OPERATING SYSTEMS 1 (SYST1)
❑ Introduction
❑ Linux Architecture
Some Linux distributions install several shells.
These might include :
gnome-terminal, konsole, xterm, rxvt, kvt, nxterm, and eterm.
User Command
Interpret
System Execute
❑ What is a “Shell”?
The “Shell” is simply another program on top of the kernel which provides a basic human-OS
interface.
▪ It is a command interpreter
✓ Built on top of the kernel
✓ Enables users to run services provided by the UNIX/Linux OS
▪ In its simplest form, a series of commands in a file is a shell program that saves having to retype
commands to perform common tasks.
user
Shell
user
Shells …
❑ Linux Shell
To check shell:
✓ You can switch from one shell to another by just typing the name of the shell.
✓ exit return you back to previous shell.
In today's computing world, automation is key, and mastering shell scripting is an essential skill for
system administrators, developers, and cybersecurity professionals. The Bash shell (Bourne Again
Shell) is one of the most widely used command-line interfaces in Linux and Unix-based systems, making
it a powerful tool for system management and process automation.
• Shell script = Broad term for scripts compatible with any shell.
• Bash script = A subset of shell scripts using Bash-specific features (A specific type of
shell script written for the Bash shell, often using its unique features).
• Portability: Use POSIX sh for maximum compatibility; use Bash for richer functionality on
Linux.
• Always check the shebang line (#!/bin/sh vs. #!/bin/bash) and test your script in the
target environment!
❑ Objectives
• Understand the basics of Shell programming and scripting
• Learn how to create and execute Shell scripts
• Explore common use cases for automation and task management
• Understand key Shell commands and syntax for effective scripting
• Gain hands-on experience through practical examples and exercises.
❑ Prerequisites
• Basic knowledge of Linux command-line usage
• Familiarity with file system navigation and permissions
• A working knowledge of text editors (e.g., Vim, Nano)
• Basic programming concepts (optional but helpful)
▪ Recommended text editors and IDEs for writing scripts (vim, nano, VS Code)
❑ Real-World Applications
▪ Scheduling tasks with cron jobs, Log file analysis and monitoring
▪ Bash programming focuses on creating logic and control flows (like loops, conditionals,
functions) within the context of the Bash shell environment.
▪ Use Case:
Bash programming is used when you want to write more complex, reusable scripts or tools
within the Bash environment. It can involve building small utilities, automating repetitive tasks, or
interacting with the operating system.
▪ Nature:
More focused on programming logic, structure, and writing code that interacts directly with the
operating system via the Bash shell. It often involves writing small, standalone programs or
scripts.
▪ Shell scripting is a broader concept that involves writing scripts for any shell (not just Bash).
Shells include Bash, Zsh, Fish, Ksh, and others.
▪ A shell script is essentially a sequence of commands written for a shell to automate tasks or
solve problems.
▪ Scope: While Bash is a specific shell, shell scripting can be done in any shell, meaning:
✓ Writing commands to automate tasks in the terminal (e.g., file manipulation, process
management)
✓ Making use of shell-specific features and commands for a variety of systems (Linux, macOS,
etc.)
✓ Shell scripting can include tools and utilities from the broader Unix/Linux ecosystem, such as
grep, awk, sed, and cut.
▪ Use Case:
Shell scripting is often used for simpler tasks like automating system maintenance (e.g.,
backups), running batch jobs, or performing regular administrative actions. It can be used across
multiple shell environments, allowing for portability if written in a standard POSIX-compliant way.
▪ Nature:
Shell scripting is more about command-line instructions that execute in sequence to automate
tasks, with less emphasis on complex programming logic (although it can still involve some).
❑ Shell Script
A shell script is a text file that contains a sequence
of commands for a Unix/Linux operating system.
❑ Shell Script
How to develop a shell script?
There are some rules to develop shell scripts.
File name :
Add .sh at the end of the file name as a file
extension.
Document structure:
▪ Declaration: You need to specify which shell will
be used for the shell script.
▪ Comment: You can add comments with # at the To successfully write a shell script, we have to do 3 things:
beginning of comments. 1. Write a script
2. Give the shell permission to execute it
Here is an example of creating a shell script using
3. Put it somewhere the shell can find it
some commands. Use vim to create a shell script
file named test.sh.
/ 1BT ‐ SYST 1 © 2024 / 2025 - Dr. Sassi BENTRAD
8. BASH PROGRAMMING AND SHELL SCRIPTING 03
❖ SHELL SCRIPTING BASICS
❑ Shell Script
Add an execution permission :
Usually, execution permission is not added when you create a file. To make a script executable :
In order to make the script executable, you need to add an Syntax: chmod +x script_name
execution permission to the file. To grant permission to the owner
of the file, run the chmod u+x command followed by the file path. To run it :
Syntax: ./script_name
For the test.sh file, grant the execution permission to the owner
user. To avoid ./
Syntax: PATH+=:.
or :
Run a shell script : PATH=$PATH:.
To run a shell script, you just need to specify the file path of the
shell script like the one below.
❑ Shell Script
Call another shell script from a shell script
You can call another shell script from a shell script.
This is like creating a child process from a parent
process.
❑ Shell Script
Call another shell script from a shell script
Add ./test_child.sh between the cat command and
the sort command.
❑ UNIX/Linux Commands
● File Management and Viewing o To understand the working of the command and
● File System Mangement possible options use (man command)
● Help, Job/Process Management o Using the GNU Info System (info, info command)
● Network Management o Listing a Description of a Program (whatis
● System Management command)
● User Management o Many tools have a long−style option, `−−help',
● Printing and Programming that outputs usage information about the tool,
including the options and arguments the tool
● Document Preparation takes.
● Miscellaneous
▪ No compiler required to run a shell script, ▪ Lines starting with # are comments except the very
because the shell acts as an interpreter when first line where #! indicates the location of the shell
reading script files. that will be run to execute the script.
▪ After you create a shell script, you simply tell the ▪ On any line characters following an unquoted # are
OS that the file is a program that can be executed, considered to be comments and ignored.
by using the chmod command to change the files’
mode to be executable. ▪ Comments are used to :
✓ Identify who wrote it and when
▪ Shell programs run less quickly than compiled ✓ Identify input variables
programs, because the shell must interpret each ✓ Make code easy to read
command inside the executable script file before it ✓ Explain complex code sections
is executed. ✓ Version control tracking
✓ Record modifications
▪ Each read statement reads an entire line. In the above example if there are less than 3 items in the response
the trailing variables will be set to blank ‘ ‘.
▪ Three items are separated by one space.
▪ Hello script exercise continued…
▪ The following script asks the user to enter his name and displays a personalised hello.
#!/bin/sh
echo “Who am I talking to?”
read user_name
echo “Hello $user_name”
▪ Try replacing “ with ‘ in the last line to see what happens.
❑ Shell Variables
▪ Variables are symbolic names that represent values stored in memory
▪ Three different types of variables :
❶ Global Variables: Environment and configuration variables, capitalized, such as HOME, PATH,
SHELL, USERNAME, and PWD.
When you login, there will be a large number of global System variables that are already defined.
These can be freely referenced and used in your shell scripts.
❷ Local Variables
Within a shell script, you can create as many new variables as needed. Any variable created in
this manner remains in existence only within that shell.
❸ Special Variables
Reversed for OS, shell programming, etc. such as positional parameters $0, $1 …
VARIABLE_NAME=variable_value
▪ Example:
a=‘abc’
b=${a}def # this would not have worked without the { } as
#it would try to access a variable named adef
▪ Example :
#!/bin/sh
a=(1 2 3)
echo ${a[*]}
echo ${a[0]}
Results : 1 2 3
1
/ 1BT ‐ SYST 1 © 2024 / 2025 - Dr. Sassi BENTRAD
8. BASH PROGRAMMING AND SHELL SCRIPTING 25
❖ SHELL SCRIPTING BASICS
Command Description
VARIABLE_NAME= variable_value Create a new variable
echo $VARIABLE To display value of a variable
env Displays all environment variables
unset Remove a variable
export Variable=value To set value of an environment variable
A shell variable take on the generalized form variable=value (except in the C shell).
$ set x=37; echo $x
37
$ unset x; echo $x
x: Undefined variable.
You can set a pathname or a command to a variable or substitute to set the variable.
$ set mydir=`pwd`; echo $mydir
The four basic logic structures needed for program development are:
o Sequential logic: to execute commands in the order in which they appear in the program.
o Decision logic: to execute commands only if a certain condition is satisfied.
o Looping logic: to repeat a series of commands for a given number of times.
o Case logic: to replace “if then/else if/else” statements when making numerous comparisons.
Functions in Bash work in a similar way as functions in other programming languages. However, there are some
rules and syntaxes that you must follow while using them in your script.
Output:
▪ Cons
o Performance slowdown
o Accurate scientific computing
❑ Summary
The best way to improve your shell scripting skills is to practice regularly and work on
projects that interest you.
Keep in mind that there are often multiple ways to solve a shell scripting problem.
Remember to always test your scripts thoroughly before using them in a production
environment.
From complex task automation to efficient data manipulation, you now possess the ability to
tackle real-world challenges with confidence.
Embrace the power of advanced shell scripting and unlock a world of automation and efficiency.
❑ Reference Books
▪ Class Shell Scripting
http://oreilly.com/catalog/9780596005955/
▪ LINUX Shell Scripting With Bash
http://ebooks.ebookmall.com/title/linux-shell-scripting-with-bash-burtch-ebooks.htm
▪ Shell Script in C Shell
http://www.grymoire.com/Unix/CshTop10.txt
▪ Linux Shell Scripting Tutorial
http://www.freeos.com/guides/lsst/
▪ Bash Shell Programming in Linux
http://www.arachnoid.com/linux/shell_programming.html
▪ Advanced Bash-Scripting Guide
http://tldp.org/LDP/abs/html/
▪ Unix Shell Programming
http://ebooks.ebookmall.com/title/unix-shell-programming-kochan-wood-ebooks.htm
Author ID : 44461052600