Bash Scripting Basics
Introduction to Shell Scripting
Bash scripting is a powerful technique for automating tasks in Unix and Linux environments. As a fundamental skill in linux command line and unix shell programming, bash scripts enable system administrators and developers to create efficient, repeatable workflows.
Core Concepts of Bash Scripting
Script Structure and Execution
A typical bash script begins with a shebang line and contains a series of commands:
#!/bin/bash
## First bash script example
echo "Hello, Linux World!"
Key Components of Bash Scripts
Component |
Description |
Example |
Shebang |
Specifies interpreter |
#!/bin/bash |
Variables |
Store data |
name="John" |
Conditionals |
Control flow |
if [ condition ]; then |
Functions |
Reusable code blocks |
function greet() { } |
Basic Script Execution Workflow
graph TD
A[Write Script] --> B[Save .sh File]
B --> C[Make Executable]
C --> D[Run Script]
Practical Script Examples
Variable Declaration and Usage
#!/bin/bash
username="DevOps Engineer"
echo "Welcome, $username!"
current_date=$(date)
echo "Current date: $current_date"
Simple Conditional Logic
#!/bin/bash
age=25
if [ $age -ge 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
Script Permissions and Execution
To run a bash script, set executable permissions:
chmod +x script.sh
./script.sh