Linux Bash Scripting - Automate Tasks in Linux

Linux Bash Scripting - Automate Tasks in Linux
Page content

Introduction

The Bourne shell is also known to most as Terminal. Bash is a superset of the Bourne shell command syntax. Bash is the standard way to get some thing automated quickly. Or to try a idea that you later want to work out in another language like C. Don’t get me wrong, Bash is a full featured programing language. With if..else statement loops and all that other good stuff.

That Sounds Hard

It does and it might be daunting for beginners to start Bash scripting. But it isn’t as hard as it looks. As long as you follow some basic guidelines then it really isn’t hard.

Programing is like riding a bicycle; you might need training wheels in the beginning but after a while they can be taken off and you can ride the bicycle without the wheels.

Let’s Write Our first Script

A Bash script always start with the identifier:

#!/bin/bash

This goes before any other lines at the top of every Bash script. Let’s make the world famous “Hello World” script. The purpose of this script is to write “Hello World” to the Terminal.

Open a file with a text editor in Terminal; we do that like this:

nano hello

If the text file doesn’t exist then it will be created. To get Linux to recognize it as a Bash script put #!/bin/bash at the top of this file.

On the next line write echo “Hello World”. Close the file by hitting ctrl->x y and enter. In order to be able to run the script, we first need to make it executable.

chmod +x hello

Now run the file:

./hello

This will write “Hello World”, without quotations, to the screen.

Congratulations; you’ve now written your first Bash script.

Often Used

When scripting in Bash, here is what you will see a lot. We will go into detail about what all of this means in a future article of the series.

if…else

while

for

echo

sleep

case

We will cover the use of variables and using option switches, and how to format a script. All of these basic rules will be discussed in more detail, starting in part two of this series.

But Why?

If, after this small introduction, you still don’t understand why you should even bother with all of this, then I ask you to keep reading. Or come back when you have run a bunch of commands for the hundredth time, and you think back to this article.

I guarantee even if you don’t have a use for Bash scripting right now, you will in the future.

This Is All About Bash Scripting But What About….

If you want to learn other programing languages we have articles for those too, here at Bright Hub. Try the following articles written by some of my fellow writers.

C Programming For Beginners By Noel Kalicharan

Java Programming For Beginners By Noel Kalicharan

Next Month Part Two In This Series.