Shell Scripting

Introduction to Shell

You've learned how to type commands into the terminal. The program that actually reads what you type, interprets it, and executes it is called the Shell.


What is a Shell?

A Shell is the command-line interpreter. It is the outermost layer of the operating system (hence the name "shell" surrounding the "kernel").

When you type ls -l and hit Enter, the Shell:

  1. Parses the text.
  2. Finds the ls program on your hard drive.
  3. Passes the -l argument to it.
  4. Returns the output to your screen.

Bash vs Zsh

There are many different shells you can use in Linux and macOS:

  • Bash (Bourne Again SHell): This is the default shell on almost all Linux distributions, including Ubuntu and Raspberry Pi OS. It is the industry standard for writing scripts.
  • Zsh (Z Shell): This is the default shell on modern macOS. It is highly customizable (often used with Oh My Zsh for beautiful themes and auto-completion).

For the purpose of scripting, we almost always write scripts intended to be run by Bash, because it guarantees they will run on any Linux server or Raspberry Pi.


What is a Shell Script?

A shell script is simply a text file containing a sequence of commands that you would normally type into the terminal one by one.

Instead of typing:

bash
sudo apt update
sudo apt install git
git clone https://github.com/my/project
cd project
./build.sh

You can put all of those commands into a single file called setup.sh. When you run the script, the shell executes them in order. This is how we automate complex toolchain setups!


The Shebang (#!)

How does the computer know which shell should execute your script? You tell it using a special first line called a "shebang".

If you want your script to be executed by Bash, the very first line of your file must be:

bash
#!/bin/bash

If you don't include this, the system will try to use the user's default shell, which might behave differently.

In the next section, we will write our first script and learn how to use variables and loops to automate repetitive tasks.

Previous
Package Managers (apt)