Page 1 of 1

Bash Scripting Basics beginner tutorial for writing bash scripts Rate Topic: ***** 2 Votes

#1 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 387
  • View blog
  • Posts: 1,663
  • Joined: 16-May 09

Posted 06 November 2009 - 11:34 AM


Hi, In this tutorial we are going to learn how to write bash scripts to do some useful stuff you may need in daily use.

Creating The Script File
fire up your favorite text editor (vim for me) and create a file with no extension, for example, I use "mybackup". So I must write this in the Terminal:
vim mybackup
Ok, now we created the file itself, what next? here we go...

Writing A Simple Script
In every bash script you write, you must define where your bash interpreter is located. But how can one find where it is? just do this in Terminal:
which bash
for me, output is: /bin/bash

Now, at first line of your script file (for me it is "mybackup") write the following:
Simply, it's a "#!" and right after it, the location of your bash interpreter you got with issuing the command "which bash". This was all need to be done in the first line. After it, we are going to actually put our own commands to be executed. The script I want to write is going to be used backup my home directory which contains my personal files and (Top Secret!) projects I do daily.

Ok, in the line after the "#!/bin/bash" in the script, we have to add the command which does the backup process, which is going to be a simple "tar" command to store user's home directory in a single tar file.
tar -cvf backup.tar /home/kian/
What this command says is: create the tar file "backup.tar" and store the contents of folder "/home/kian" which is my home directory. The "-v" option tells the tar command to print detailed info while executing.

Ok, now I want to show you how to print sentences from your script, you just have to use the command "echo" and give it a sentence to print on screen.
tar -cvf backup.tar /home/kian/
echo "Backup Created Successfully!!! :D"
Don't forget to put your text between quotes!

Is there a way to put comments so that the script will be more readable by users? Yes! you just have to put a "#" mark at the first of the line you want it to be commented. Don't mix it with the "!#" we have at the first line, that one is not for commenting. Here, the completed script looks like this:
#Creating Tar File - Backing Up User's Directory
tar -cvf backup.tar /home/kian/
#Printing A Sentence On Screen Using Echo
echo "Backup Created Successfully!!! :D"

Finishing It Up!
Now that our script is finished, save the file and issue the following command in Terminal to make the script file executable:
chmod ugo+x mybackup

To execute the code, write this in Terminal:

Now our script is ready to be used! B)

Hope this tutorial helped you get started with bash scripting.

Is This A Good Question/Topic? 10
  • +

Page 1 of 1