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 mybackupOk, 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 bashfor me, output is: /bin/bash
Now, at first line of your script file (for me it is "mybackup") write the following:
#!/bin/bashSimply, 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.
#!/bin/bash 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.
#!/bin/bash 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:
#!/bin/bash #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!
Hope this tutorial helped you get started with bash scripting.