Writing Your First Shell Script

Introduction to Shell Scripting

Hello! Welcome to your first step into the world of shell scripting. In this lesson, you will learn how to write a basic shell script. Shell scripts are powerful tools used to automate tasks on Unix-like systems.

A shell script is a file that contains a series of commands. Think of it as a way to tell your computer to perform multiple operations sequentially. By learning shell scripting, you can save time on routine tasks and even handle complex operations that would otherwise require a lot of manual effort.

Before diving into specifics, it's worth noting that bash (Bourne Again Shell) is one of the most popular shells used for scripting. Other popular alternatives include zsh, sh, and ksh, but for this course, we will focus on bash.

Creating and Running a Shell Script

Let's begin by creating a simple shell script that prints "Hello, World!" to the screen. This classic example serves as a foundation, helping you understand the script's structure.

Here's what the script looks like:

#!/bin/bash

# Simple script to print "Hello, World!"
echo "Hello, World!"

Suppose this script is located in a file called hello_world.sh. Before running the script, you need to make it executable. To do this, navigate to the directory where the script is saved and run:

chmod +x hello_world.sh

chmod is the command used to change file modes or access permissions, and +x adds the execute permission to the file.

Finally, the command to run the script from the terminal is:

./hello_world.sh

Running the script above results in "Hello, World!" being output by the console. In the CodeSignal IDE, clicking the "Run" and "Submit" buttons automatically calls the ./solution.sh command. This is how your solution files are run by Cosmo!

Now let's look at each line of the script in more detail.

Understanding The Shebang

The shebang (#!/bin/bash) is essential in shell scripts as it defines the interpreter to be used when running the script. It is the absolute path to the interpreter's executable file. While we use /bin/bash here, you could use /bin/sh for more basic scripts or /bin/zsh for enhanced scripting functionalities. Using the appropriate interpreter ensures your script runs even on different systems.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal