Writing Bash Scripts

Learn how to write Bash scripts.

Throughout this course, you’ve worked with the Bash shell. You’ve used various commands and programs to work with files, directories, text, and even data over a network.

What is a Bash script?

A Bash script is a file that contains a list of commands we want the computer to execute. When we run the script, the commands will execute one at a time, sequentially, until all of the commands are run. We can use any command we’d normally type in our terminal, which means we can use everything we’ve learned about the command-line interface in a script. But Bash scripts support more than just commands. We can use variables, conditional statements, loops, and arrays. We can get input from files, pass command-line arguments, or even prompt the user for input for a more interactive experience.

To explore these concepts further, we’ll create a script that generates the files and directories for a new website project. When we’re done, we’ll be able to issue a single command to bootstrap a new project.

But before we dive into the website creation program, let’s get comfortable with creating and running Bash scripts by writing the obligatory “Hello World” program.

Creating a Bash script

Let’s switch to our home directory and create a new file called hello_world.sh. The .sh extension isn’t required, but it’s handy when developing because text editors use it to enable syntax highlighting for shell scripting.

cd
touch hello.sh

We add the following statement to the file, which uses the echo command to print Hello World!:

echo "Hello World!"

When we run this script, it’ll execute the script’s contents and print the result to the screen.

At the prompt, we use the bash command to run the script:

bash hello.sh

Run the complete code on the terminal below for practice.

cat << "EOF" > hello.sh
echo "Hello World!"
EOF
clear
bash hello.sh

Get hands-on with 1400+ tech skills courses.