In Unix or Unix based operating systems, a shell is a program that interprets the command and acts as an intermediary between user and kernel. There are different types of shells are available on different Unix based systems. These all have similar functionality but different syntax and capabilities. You can automate a task by writing a script. Other operations of a script are file manipulation, program execution, etc.
What is a shell script
A shell script is a computer program or simply a text file which contains a sequence of command that is being executed by an interpreter called a shell on Unix or a Unix based machine. There are various dialects are used for different types of shells to write a script which is known as a scripting language. Now we will proceed further in our discussion about the writing and executing a shell script follow the steps that are given below.
Know your shell type
Majorly a shell can be divided into two types –
- bourne shell (sh)
- c shell (csh)
There are many other types of shells are also available like bourne again shell (bash), Korn shell (ksh), TC shell (tcsh), Z shell (zsh), etc. but all of these are the descendants and improved versions of either of two that are given above. Since different types of shells have different syntax and capabilities. So it is important to know which type of shell you are using in your system. You can check the shell type by typing /etc/shells in your terminal.
or executing the command echo $0 into your terminal.
Above you can see the type of shell that I am using.
Write your script
A script is nothing but a set of commands that is to be executed on a Unix or Unix based machines. You can use any text editor to write your script. But remember to save it with .sh extension.
As you can see the above script first line contains #!
which is known as shebang and it is followed by a symbolic link of the shell. And you can start commenting by using the #
symbol. echo
is used to display some text. read
is a keyword used to take input from the console. t is a variable contains current time. %r
is a format used for 12 hour clock time. date
is a keyword used to get date and time.
Make the script executable
By default, a user does not have permission to execute it. So we have to provide permission to execute it use chmod
command to change the permission. To know more about file permissions you can read File ownership and permissions in Linux/Unix
here we added executable permissions to all that is user, group and other users.
Execute your script
To execute your script type the following command into your terminal./hello.sh
Once the script executed the output of the above script will be displayed in the terminal as given above. I hope it will develop a good understanding of the topic. If still you have any other query regarding it you can write us in comment below.