Table of Contents
Getting Ready to Write a Script
A shell script is simply a text file that contains commands the shell can execute in order. You already know how to run single commands in a terminal. A script lets you save a series of those commands and run them all at once with a single instruction.
To write your first script, you only need three things. You need a text editor, such as nano, to create the file. You need the shell itself, usually bash, to interpret the file. Finally, you need a way to run the script, either by calling it explicitly with the shell or by making it executable and running it like a program.
The shell used in this chapter is bash, which is the default on many Linux distributions. Other sections later in the course will cover differences between shells, so here you can assume that commands are executed by bash unless you specify otherwise.
Creating a Simple Script File
Start by opening a terminal and creating a new file with nano. For example, you can create a file called first.sh in your home directory.
nano first.shInside the editor, type these lines:
echo "Hello, world!"
Save and exit the editor. In nano, you press Ctrl+O to write the file, press Enter to confirm the file name, and then Ctrl+X to exit.
You now have a text file that contains a single shell command. The shell can read this file and execute the command exactly as if you had typed it directly into the terminal.
Running a Script with bash
At this point, your file is just a regular text file. The shell does not automatically treat it as a program. The simplest way to run it is to call bash and give it the file name.
From the same directory where first.sh is saved, run:
bash first.sh
The shell reads first.sh and executes the command it finds inside. You should see the text Hello, world! printed on the terminal.
If you see an error saying something like No such file or directory, check that you are in the correct directory. You can list the files with:
ls
If the listing contains first.sh, but bash first.sh still fails, check that the file name is spelled exactly the same, including case. Linux treats First.sh and first.sh as different names.
At this stage you are running the script explicitly with bash. The shell reads the commands and does not care what the file is called. Scripts often use the .sh extension for clarity, but the extension is not required for the shell to run them this way.
Adding a Shebang Line
To make a script more self contained, you can add a special first line that tells the system which interpreter to use. This line is called a shebang. It starts with #! followed by the full path to the interpreter.
For a basic bash script, the shebang usually looks like this:
#!/bin/bashEdit your script so it looks like this:
#!/bin/bash
echo "Hello, world!"
The shebang is read when you run the script as a program on its own. It instructs the kernel to start /bin/bash and give it your script as input. If you run the script explicitly with bash first.sh, the shebang is not required, because you are already choosing the interpreter.
Important rule:
A shebang line must be the very first line in the script, with no leading spaces and no blank lines above it.
If the shebang is not exactly on the first line, the system treats it as an ordinary comment and ignores it when deciding how to run the file as a program.
Making the Script Executable
To run the script directly, without typing bash in front, the script file must have execute permission. How permissions work in detail belongs to later chapters. Here, you only need one command to mark a script as executable for yourself.
From the directory containing first.sh, run:
chmod +x first.shThis adds execute permission to the file. You do not see any output if it succeeds. You can verify that the file is now executable with:
ls -l first.sh
You should see a line starting with something like -rwxr-xr-x. The x characters indicate execute permissions.
Now you can run your script directly by specifying a path to it. Since the current directory is not in your command search path, you normally use a relative path starting with ./:
./first.sh
The leading ./ tells the shell to look for first.sh in the current directory. Without this, the shell would only search directories listed in your PATH, which usually does not include the current directory for safety reasons.
If you see an error such as Permission denied, it usually means the script is not executable. In that case, check the permissions again and run chmod +x first.sh if needed.
Using Comments in Scripts
Comments in scripts are lines that start with #. The shell ignores everything after # on that line, except when it appears as the shebang on the very first line. Comments are useful to explain what your script does or to temporarily disable a line of code.
Extend your script like this:
#!/bin/bash
# This is my first shell script
# It prints a friendly message
echo "Hello, world!"
echo "This is my first script."
When you run ./first.sh again, the output only shows the two echo lines. The comments are there for humans who read the script, not for the shell.
You can also put a comment at the end of a line that contains a command. Everything after # is ignored.
echo "Another message" # This text will not be executedAs your scripts grow, comments help you understand later why you wrote something, especially if you return to the file after some time.
Using Arguments with Your Script
Scripts can accept parameters from the command line, known as arguments. Each argument is available in the script through special variables like $1, $2, and so on. The variable $1 holds the first argument, $2 the second, and so on. The variable $0 contains the script name itself.
Modify your script to use an argument:
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"Now run the script with an extra word after it:
./first.sh Alice
You should see that $0 prints something like ./first.sh and $1 prints Alice. If you run ./first.sh Bob, the first argument changes accordingly.
You can combine arguments with text. For example:
#!/bin/bash
echo "Hello, $1!"
Running ./first.sh Alice will print Hello, Alice!. If you run the script without any arguments, $1 will be empty, and the output will reflect that. Handling optional or missing arguments properly belongs to later topics, but this simple example shows how the script can react to the values you pass when you run it.
Multi-line Scripts and Execution Order
A script can contain many lines. The shell reads the file from top to bottom and executes each command one after the other. This allows you to chain actions in a predictable sequence.
As a small example, create a script that prints a greeting, shows the current date, and then prints the working directory.
#!/bin/bash
echo "Starting script..."
date
pwd
echo "Script finished."When you run this script, you see the messages and command outputs in the order they appear in the file. This is all a shell script really is. It is a list of shell commands that you could have typed manually, written into a file, and executed as a group.
You can always test parts of your script interactively in the terminal first. If a command works as expected on its own, you can then add it to your script. This is a simple way to build scripts gradually and avoid confusion when something does not behave as expected.
Running Scripts from Different Locations
So far you have run your script from the same directory where it lives. Often, you will want to run a script from somewhere else. You can always give the shell either a relative path from your current directory or an absolute path that starts at the root.
For example, if your script is in /home/alex/first.sh, you can run:
bash /home/alex/first.shor, if it is executable and has a correct shebang:
/home/alex/first.sh
If you are currently in /home, you can run it using a relative path:
bash alex/first.shor, if executable:
alex/first.sh
Remember that the current directory, represented as ., is just another path. That is why ./first.sh works. The . stands for “here,” and ./first.sh says, “run the file named first.sh that is in the current directory.”
Later chapters that cover paths in more detail will show you how relative and absolute paths behave more generally. For now, the key idea is that any time you want to run a script file, you must tell the shell where to find it.
Using Exit Status in Simple Scripts
Every script finishes with an exit status, which is a number that indicates success or failure. By convention, 0 means success and any nonzero value means some kind of error. Unless you say otherwise, a script exits with the status of the last command it ran.
You can set the exit status explicitly in a script with the exit command. For example:
#!/bin/bash
echo "Doing something..."
exit 0
When this script finishes, it returns 0 to the shell. You can inspect this value from the terminal with the special variable $? immediately after running the script:
./first.sh
echo $?
If you change exit 0 to exit 5, you will see 5 printed instead. Later topics will show how to use exit status to control logic, error handling, and how other programs respond when they call your script. For now, understand that every script ends with a numeric status, and you can set it yourself when needed.
Summary of the First Script Workflow
You now know the basic steps to create and run a shell script. First, you write the script as a plain text file that contains shell commands. You optionally add a shebang line at the top to define the interpreter, and you save the file. You run the script by either invoking bash directly and passing the file name, or by making the script executable and running it via its path such as ./first.sh. You can add comments to explain the code, accept arguments through variables like $1, and see that the script runs commands in order from top to bottom.
These are the essential mechanics of writing your first script. Later sections will build on this by introducing variables, conditionals, loops, and functions so you can make your scripts respond intelligently to different situations.