Getting Started with Shell Scripting

Tutorial 2 of 5

1. Introduction

This tutorial aims to help you get started with shell scripting. By the end of this guide, you'll understand what shell scripting is, why it's important, and how you can start writing your first script.

What will you learn?

  • The basics of shell scripting
  • How to write your first shell script
  • Best practices in shell scripting

Prerequisites

  • Basic knowledge of Linux commands
  • Access to a Linux system

2. Step-by-Step Guide

Shell scripting is a powerful tool that allows you to automate commands and tasks on a Linux system. It's like programming, but for your shell. A shell is a user interface that allows you to access various services of an operating system.

Writing your first script

  1. Open your text editor, type the following lines, and save the file as firstscript.sh
#!/bin/bash
# This is a comment
echo "Hello, World!"
  • #!/bin/bash is known as a shebang. It tells the system that this script needs to be executed through the bash shell.
  • # This is a comment is a comment. It's ignored by the shell and won't be executed.
  • echo "Hello, World!" prints "Hello, World!" to the terminal.

  • Give the script the correct permissions using chmod:

chmod +x firstscript.sh
  1. Run the script:
./firstscript.sh

3. Code Examples

Example 1: A Shell Script to Say Hello

#!/bin/bash
# A simple shell script to print a greeting
name="John"
echo "Hello, $name!"
  • name="John" sets a variable name to the value "John".
  • echo "Hello, $name!" prints "Hello, John!" to the terminal.

Example 2: A Shell Script to List Files

#!/bin/bash
# A shell script to list all files in the current directory
for file in $(ls)
do
   echo $file
done
  • for file in $(ls) loops over every file in the current directory.
  • echo $file prints the name of each file.

4. Summary

In this tutorial, we've covered the basics of shell scripting, how to write a shell script, and provided two simple examples. The best way to learn is by doing, so try to modify the examples or create your own scripts.

5. Practice Exercises

Exercise 1:

Write a shell script that asks for your name and prints "Hello, [Your Name]!"

Exercise 2:

Write a shell script that prints the current date and time.

Exercise 3:

Write a shell script that lists all the files in a directory specified by the user.