Creating & Executing Shell Scripts: Vim Basics, File Extensions, and the Shebang
This chapter covers the fundamental steps required to create, edit, and configure shell scripts in a Linux environment. You will learn how to navigate the Vim editor, organize your workspace using Git and directories, understand the critical role of the Shebang (#!), and locate your system's shell interpreters.
1. Understanding the Vim Editor: Modes and Basic Navigation
Before writing shell scripts, you must know how to interact with terminal-based text editors. Vim is one of the most common and powerful command-line editors available in Linux.
Unlike standard graphical text editors, Vim operates using distinct modes. When you first open a file using Vim, you cannot immediately type text. You must switch to the correct mode.
The Two Primary Vim Modes
- Command (Normal) Mode: This is the default mode when Vim opens. Any keys you press are interpreted as commands (e.g., copy, paste, delete, or exit) rather than literal text.
- Insert Mode: This mode allows you to write and edit text inside the file, just like a regular notepad.
Step-by-Step Vim Workflow
To create and edit a basic text file:
- Open or Create a File:
BASH
vim hello.txt - Enter Insert Mode: Press the
ikey on your keyboard. You will see-- INSERT --appear at the bottom of the terminal window. - Write Text: Type your content (e.g.,
This is a new file). - Exit Insert Mode: Press the
Esckey. This returns you to Command Mode. - Save and Exit: Type the command sequence
:wq(Write and Quit) and pressEnter. - Exit Without Saving: If you made a mistake and want to discard changes, type
:q!and pressEnter.
To verify that your file was saved successfully, use the cat command to display its contents:
cat hello.txt
2. Real-Life Analogies: Vim Modes & Movie Production Houses
To build an intuitive mental model of these technical concepts, consider the following real-world analogies:
Analogy 1: Vim Modes as a Locked Building
Imagine entering a secure building.
- Command Mode is like standing in the lobby with security. You can issue commands (ask for directions, request to leave, or show your ID), but you cannot paint the walls or rearrange the furniture.
- Insert Mode is like unlocking an office door and stepping inside with your tools. Now you can write on the whiteboard, edit documents, and make physical changes. Pressing
Escis the equivalent of stepping back out into the lobby.
Analogy 2: The Shebang as a Movie Production House Logo
When you watch a movie (like the Bollywood comedy Hera Pheri), the very first frame shows the logo of the production house (e.g., "This movie is brought to you by XYZ Productions"). This logo tells the theater and the audience exactly who produced the film and how it should be presented.
Similarly, the Shebang (#!/bin/bash) at the top of a script is the "production house logo" for your code. It tells the operating system's interpreter: "This script is brought to you by the Bash Shell. Please use Bash to run these commands."
3. Setting Up the Workspace & File Extensions
When writing code, file extensions act as indicators for both developers and operating systems to identify the file type.
Setting Up Your DevOps Directory
To keep your scripts organized, it is best practice to maintain them inside a version-controlled directory. You can clone a Git repository and set up structured daily folders:
# Clone the course repository
git clone https://github.com/your-repo/shell-scripting-for-devops.git
# Navigate into the cloned directory
cd shell-scripting-for-devops
# Create a directory for Day 1
mkdir day01
# Navigate into the Day 1 directory
cd day01
4. Demystifying the Shebang (#!)
When you write a shell script, the operating system needs to know which command interpreter to use to execute the lines of code. This is defined on the very first line of the script using a special character sequence known as the Shebang (also written as #!).
#!/bin/bash
Anatomy of the Shebang
#(Hash): In shell scripting, a hash symbol at the start of a line normally denotes a comment (ignored by the interpreter).!(Bang): When combined immediately with a hash (#!) at the very first line of a file, it overrides the standard comment behavior./bin/bash: This is the absolute path to the Bash interpreter binary on your system.
How the Interpreter Processes the Script
When you execute a script, the kernel reads the first line. If it detects #!/bin/bash, it starts a Bash subshell process and passes the rest of the script's lines to that process one by one.
Note: If you do not specify a Shebang, the system will attempt to run the script using your current active shell. This can cause unexpected errors if your script uses Bash-specific syntax (Bashisms) but is executed by a system running
shorzsh.
5. Locating Your Shell Interpreter (which bash)
Different Linux distributions may store shell binaries in slightly different directories. To ensure your Shebang points to the correct location, you can query the system using the which command.
The which command searches your system's PATH environment variable and returns the absolute path of the executable binary.
which bash
Example Output:
/usr/bin/bash
(Note: On many modern Linux distributions, /bin is a symbolic link to /usr/bin, meaning both #!/bin/bash and #!/usr/bin/bash will resolve to the same interpreter).
6. Complete Flow Walkthrough: Creating hello.sh
Let's put all these concepts together to create and save your very first functional shell script.
Step 1: Create the file
vim hello.sh
Step 2: Write the Script
Press i to enter Insert Mode, and type the following lines:
#!/bin/bash
# This is a comment. It will not be executed by the shell.
echo "Hello, World! This is my first shell script."
Step 3: Save and Exit
Press Esc, type :wq, and press Enter.
Step 4: Verify File Contents
cat hello.sh
Execution Flow:
Summary and Key Takeaways
- Vim Modes: Vim uses Command Mode for navigation/file operations and Insert Mode (activated by pressing
i) for typing text. - Saving in Vim: To save changes and exit, press
Escto return to Command Mode, then type:wqand pressEnter. - File Extensions: While Linux is extension-agnostic, using
.shfor shell scripts is a critical best practice for developer clarity and editor syntax highlighting. - The Shebang (
#!): Must be placed on the absolute first line of your script to tell the operating system which interpreter to use to run the file. - Locating Shells: Use the
which bashcommand to find the exact path of the Bash binary on your host machine. - Comments: Any line starting with
#(except the Shebang on line 1) is treated as a comment and is ignored during script execution.