Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Bash Scripting Basics

Introduction

Bash scripting is a powerful way to automate tasks in a Linux environment. This lesson will introduce you to the basics of writing and executing bash scripts.

What is Bash?

Bash, or Bourne Again SHell, is a command language interpreter for the GNU operating system. It allows users to execute commands and scripts to automate tasks.

Getting Started

To start writing bash scripts, you need a text editor (like nano or vim) and access to a terminal.

Creating Your First Script

#!/bin/bash
echo "Hello, World!"

Save this as hello.sh and run it using:

bash hello.sh

Basic Syntax

Bash scripts consist of a series of commands. The basic syntax includes:

  • Comments start with #
  • Commands can be executed in succession
  • Use echo to output text

Variables

Variables are used to store data. They can be defined as follows:

name="John"
echo "Hello, $name"
Note: No spaces around the equals sign when defining variables.

Control Structures

Control structures allow you to control the flow of your scripts. Here are some examples:

If-Else Statement

if [ "$name" == "John" ]; then
    echo "Your name is John."
else
    echo "Your name is not John."
fi

For Loop

for i in {1..5}; do
    echo "Number $i"
done

Functions

Functions help to organize your script into reusable blocks of code. Here's how to define and call a function:

function greet {
    echo "Hello, $1"
}

greet "Alice"

Best Practices

  • Use comments to explain your code.
  • Test scripts in a safe environment before deploying.
  • Make scripts executable with chmod +x script.sh.
  • Use meaningful variable names.

FAQ

What file extension should I use for bash scripts?

While not mandatory, it is a common practice to use the .sh extension for bash scripts.

How do I make a script executable?

You can make a script executable by running chmod +x script.sh.

Can I run bash scripts in Windows?

Yes, you can run bash scripts on Windows using WSL (Windows Subsystem for Linux) or Git Bash.