Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Bash: Shell Scripting Language

Introduction to Bash

Bash (Bourne Again Shell) is a popular command-line interpreter and scripting language primarily used in Unix and Linux environments. It provides a powerful interface for interacting with the operating system, automating tasks, and writing shell scripts.

Basic Syntax and Usage

Bash scripts are plain text files containing a series of commands that are executed in sequence. Here’s an example of a simple Bash script:


#!/bin/bash

# This is a comment
echo "Hello, World!"
                

In this example:

  • #!/bin/bash specifies the interpreter (Bash) for the script.
  • # This is a comment is a comment line.
  • echo "Hello, World!" prints "Hello, World!" to the standard output.

Variables and Data Types

Bash supports variables to store data and perform operations. Variables in Bash are untyped, meaning they can hold any type of data.


# Variable declaration and assignment
NAME="John"
AGE=30

# Print variables
echo "Name: $NAME"
echo "Age: $AGE"
                

In this example, $NAME and $AGE are variables holding string and integer values, respectively.

Control Structures

Bash supports various control structures for conditional execution and looping:


# Conditional statement
if [ $AGE -ge 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

# Looping example
for i in {1..5}; do
    echo "Count: $i"
done
                

In this example, an if statement checks if $AGE is greater than or equal to 18, and a for loop iterates from 1 to 5.

Functions

Bash allows defining and calling functions to encapsulate reusable code:


# Function definition
say_hello() {
    local name=$1
    echo "Hello, $name!"
}

# Function call
say_hello "Alice"
                

This example defines a function say_hello that accepts a parameter name and prints a personalized greeting.

Conclusion

Bash scripting is a versatile tool for automating tasks, managing system configurations, and writing efficient shell scripts in Unix and Linux environments. Mastering Bash enables developers and system administrators to streamline workflows and improve productivity.