Shell Scripting Basics
Introduction to Shell Scripting
What Is a Shell Script?
Think of a shell as a conversation you have with your computer. You type a command, and the computer responds. This conversation happens in a command-line interpreter, and one of the most common interpreters on Linux and macOS is called Bash, which stands for Bourne Again Shell.
Now, imagine you have a set of commands you type over and over again. Instead of manually typing them each time, you could write them down in a file and tell the computer to run all of them in order. That file is a shell script. It’s like giving your computer a to-do list.
A shell script is a text file containing a sequence of commands that the shell can execute.
People use scripts to automate repetitive tasks, like backing up important files every night, renaming hundreds of photos at once, or setting up a new computer with all their favorite software. It saves time and reduces the chance of human error.
Your First Script
Let's create our first script. A long-standing tradition in programming is to make your first program display the text "Hello, World!" on the screen. It's a simple way to confirm that everything is working.
A shell script is just a plain text file. You can create it with any text editor. We'll name our file hello.sh. The .sh ending isn't required, but it's a common convention that helps everyone (including us) recognize it as a shell script.
#!/bin/bash
# This is a comment. The shell ignores it.
echo "Hello, World!"
Let's break this down. The first line is special, and we'll come back to it. The line starting with a # is a comment; it's a note for humans, and the computer ignores it. The last line uses the echo command, which simply prints whatever text follows it to the terminal.
Making It Run
Just creating the file isn't enough. We need to tell the system how to run it and give it permission to be run.
The first line,
#!/bin/bash, is called a shebang. It tells the operating system which interpreter to use to run the script. In this case, it's the Bash shell, which is located at/bin/bash.
Next, we need to make the file executable. For security, new files you create can't be run as programs by default. We can change this with the chmod (change mode) command. Using +x adds execute permission to the file.
chmod +x hello.sh
With that done, our script is ready to go. To run it, you type ./ followed by the script's name. The ./ tells the shell to look for the file in the current directory.
./hello.sh
If everything is set up correctly, you'll see Hello, World! printed in your terminal. You've just written and executed your first shell script.
What is the primary purpose of a shell script?
Which command is used to make a script file, named myscript.sh, executable?