Module Eight - Session 26: Shell Scripts

What will I be learning?

We will learn about shell scripting. This will be the major focus of this module. One of the reasons we will focus on shell scripts in detail is the Linux startup scripts are actually shell scripts. Being able to read/understand these scripts is important. Also, being able to create your own will allow you to create or modify scripts of your own as needed.

After this chapter I should be able to...

You should be able to write a basic shell script to perform a simple task. Your basic shell script should contain variables, conditionals and/or looping.

What should I practice?

As you have taken ICS 111 you should understand the basics of programming. You should understand what a for loop does, what a while loop does, and conditional statements. A variable shouldn't be an unknown entity for you. Shell scripting is a way of programming and automating things on your Linux system to make your life easier. Here is a quick little story about how I used shell scripting recently to save time.

I was asked to help rename years worth of files into a standard naming convention. I was asked to rename about 1/3 of all the files and it had to be close to 75-100 files (it was years worth). If I didn't know how to write a shell script I would have had to manually rename all the files one by one. Instead, I wrote a shell script, extracted the data I needed from the file name and I then renamed the file as I wanted it to be named. I ran the file in a directory that contained all the files that needed to be renamed. It took me maybe 15-20 minutes to create the script, and took about 2 minutes for the script to run. Then using the script I completed the other 2/3 of the files for my peers to make their life easier. Something that people thought would take days to complete I did in under an hour of time. Enough story time, let us jump into some basics of shell scripting.


hello1.sh

#!/bin/bash

echo Hello World

I'll explain the components of the shell script. To start with, the name of the shell script is not important. I've placed the name of the shell script, which is just a plain text file as the heading for the section. The first line of the file is the shebang (#!) and then shell we wish to use. You can use any type of shell you wish, you just need to make sure to provide the path to it.

The next line we have is an echo statement. This will display the text after it, notice we don't have any quotes or a semicolon to end the line.

Once you've created your shell script and saved it, you have to make sure it is executable, so give it the proper permissions.

You can then run the shell script be doing: ./hello1.sh.

Output: Hello World



Original webpage by Petersen Gross, modified by William Albritton.