Suppose there was no shell, You can’t use command like play to play a music file or cd to change a directory or even ls to list the files.
1. Create a file (touch or use vi)
2. Put the series of commands in the file
3. Save the file (Give it a name: file_name)
4. Change the mode of this file to executable state (use chmod: chmod 0744 file_name)
5. Finally execute the file
i.e., simply write ./file_name and you are doneWonderful! never again you need to repeat those stupid actions(commands) and you have created a new command: file_name to achieve all those steps in one command.This is called shell scripting.
Let’s take a simple example.
Suppose you are a programmer, and if you have written programs like count.c test.c and the main function is in the program main.c.
Normally you would first create object files for the program.
count.o and test.o
$ gcc -c test.c count.c
This creates the respective object files.
Next you would compile your main program main.c along with the object files
$ gcc -o count main.c count.o test.o
This generates an output file called ‘count’, which you would run
This is the series of commands that you would do normally. And suppose you make small changes to test.c and main.c, you would have to again repeat all the above steps
Let’s write a small shell script for that
1. Open a file first.sh
#! /bin/sh #normally required to tell which shell to use (There are many shells like tcsh, bash, csh…)
# Choose the one you like
# Note a phrase with # starts the comment. You can write anything in the line after # and the shell will not
# try to interpret it.
gcc -c test.c count.c gcc -o count main.c count.o test.o ./count
3. Save the file
4. Change permissions of the file so as to give execute permissions from the program
$ chmod u+x first.sh
5. Now your shell script is ready. Now execute the shell script
Thus in a shell script, you can write a series of commands which you perform repeatedly. And from next time onwards, execute the shell script. So there is no need to repeat the commands again, but achieve it with a single command (shell script you wrote now will act as a command)