๐ Day 4 - Bash Scripting -2 #90DaysOfDevOps ๐
1. Bash Scripting Basics:
What is Bash Scripting? Bash scripting involves creating a sequence of commands executed by the Bash shell, enhancing automation and repeatability.
Advantages of Bash Scripting:
Facilitates system administration tasks.
Efficient management of system resources.
Automates routine tasks, improving productivity.
Where can Bash Scripting be Used? Bash scripting finds applications in databases, web servers, cloud services, and various other environments.
Bash and Shell: Bash, the default shell for Unix/Linux, executes commands read from input devices like keyboards.
Basic Bash Commands:
date: Displays the current date.pwd: Shows the present working directory.ls: Lists the contents of the current directory.echo: Prints text to the terminal.cd: Changes the directory.mkdir: Creates a new directory.touch: Creates a new file.rm: Removes a file or directory.cp: Copies a file or directory.mv: Moves or renames a file or directory.grep: Searches for a pattern in a file.chmod: Changes the permissions of a file or directory.sudo: Executes a command with administrative privileges.
Adding the Shebang: Bash scripts start with a shebang (#!/bin/bash), followed by the Bash shell path.
2. Variables and Data Types:
Variable Naming Conventions:
Variables start with a letter or underscore.
They can contain letters, numbers, and underscores.
Case-sensitive and descriptive names are recommended.
Avoid using reserved keywords as variable names.
Input and Output in Bash Scripts:
Reading user input using the
readcommand.Reading from files (
< input.txt).Command-line arguments (
$1,$2, etc.).
3. Conditional Statements and Looping:
Conditional Statements:
Using
if/elsefor conditional execution.Example:
if [ $a -gt 60 -a $b -lt 100 ].
Looping:
whileloop example:
bashCopy code#!/bin/bash
i=1
while [[ $i -le 10 ]]; do
echo "$i"
((i += 1))
done
4. Scheduling Scripts using Cron:
Cron Job Syntax:
* * * * *represents minute, hour, day, month, weekday.Example:
0 0 * * * /path/to/script.shruns a script daily at midnight.
Examples of Scheduling Cron Jobs:
Running a script every 5 minutes:
*/5 * * * * /path/to/script.sh.Running a script from Monday to Friday at 6 am:
0 6 * * 1-5 /path/to/script.sh.
5. Debugging and Troubleshooting Bash Scripts:
Debugging Techniques:
Use
set -xto trace execution.Check exit codes (
$?).Utilize
echostatements for debugging.Use
set -eto exit immediately on error.
Troubleshooting Cron Jobs:
- Verify logs located at
/var/log/syslog.


