What is Shell Scripting?
Well now you know about shell commands, lets dive in into it further. Many times you want to execute a same set of commands in the terminal say you want to manipulate a bunch of files, or you want to create a bunch of directories etc. In such scenarios it is time consuming to execute each command line by line. Worry not! shell scripting is a easy ways to automate your terminal commands.
Why Shell Scripting?
- It is easy to use
- It can get input from user or a file
- You can create your own commands
- Saves lot of time
- Can be used for automating system administration
Getting started With Shell Scripting
Our first shell script
open up your editor and type the following
#This is a comment #my first shell script echo "Welcome to superX"
now save the file as first_script.sh. Note that we save the file with an extension ".sh" it means a shell script file. This is only for our understanding the Linux kernel never cares about the extension.
Running our first script
shoot up the Terminal. cd to the folder where the script is residing. In our case it is home/raghuram/scripts. So
raghuram@hisTerminal:~$ cd ~/scripts/ raghuram@hisTerminal:~/scripts$
Note we have used a shorthand for /home/raghuram (i.e) ~. The ~ (pronounced as Tilde) represents the current home directory.
Now we need to give executing permission for our script in order to run. To do that,
raghuram@hisTerminal:~/scripts$ chmod 755 first_script.shthe command
chmodchanges the permission of the file. Now our script is ready to run. To run it.
this will produce the following result.
Welcome to SuperX
hurray!! You have successfully ran your first shell script. You can write up a bunch of commands in the text file and they will be run line by line. eg:
mkdir test cd test touch file1 file2 file3 echo writing to first file > file1 echo writing to second file > file2 echo writing to third file > file3 echo writing complete
the above code creates a directory test and creates 3 files file1 file2 file3 in it(using touch command). then we write into those files. The ">" redirects the output from standard output(i.e) the screen to the file.
So we have run our first shell script. Note that this is not a definitive guide for shell scripting. Shell scripting is far more advanced. It even supports iteration and selection which will be covered in later sections.