Creating and Running Your First Shell Script

Tutorial 4 of 5

Creating and Running Your First Shell Script

1. Introduction

This tutorial aims to guide you through the process of creating and running your first shell script. By the end of this tutorial, you will know how to write, save, and execute a shell script.

What You'll Learn

  • Understanding shell scripting basics
  • Writing your first shell script
  • Saving and executing the script

Prerequisites

  • Basic knowledge of the Linux/Unix command line
  • Access to a Unix/Linux system (You can use online Linux terminals or Linux installed system)

2. Step-by-Step Guide

Shell scripting is a way to automate repetitive tasks on UNIX-like operating systems. It involves writing a series of commands for the shell to execute. Here's a step-by-step guide to creating your first shell script:

Creating the Script

  1. Open your terminal.
  2. Use a text editor like nano, vi, or gedit to create your script. For example, nano myscript.sh.
  3. Write your script in the editor.
  4. Save and exit the editor (In nano, press Ctrl+X, then Y, then Enter).

Running the Script

  1. Make your script executable by running chmod +x myscript.sh.
  2. Run your script by typing ./myscript.sh.

3. Code Examples

Here's a simple script and an explanation of what it does:

#!/bin/bash
# This is a simple shell script
echo "Hello, World!"
  • #!/bin/bash: This line is called a shebang. It tells the system that this script should be run with bash shell.
  • # This is a simple shell script: This is a comment. It's for humans to read and doesn't affect how the script runs.
  • echo "Hello, World!": This line prints "Hello, World!" to the terminal.

When you run this script, you should see:

Hello, World!

4. Summary

In this tutorial, you've learned how to create and run a shell script. You now know how to write scripts, make them executable, and run them.

Going forward, you can start learning more advanced shell scripting concepts like variables, conditionals, and loops. Here are some resources to help you:

5. Practice Exercises

Here are some exercises to help you practice:

  1. Write a script that prints "Hello, [your name]!".
  2. Write a script that prints the current date and time.

Solutions:

  1. echo "Hello, [your name]!": Replace "[your name]" with your actual name. The echo command will print whatever comes after it.

  2. date: The date command prints the current date and time.

Remember, the best way to learn how to write scripts is by writing scripts. So keep practicing!