shell script:- Normally shells are interactive. It means shell accept command from you (via keyboard) and execute them. But if you use command one by one (sequence of ‘n’ number of commands) , the you can store this sequence of command to text file and tell the shell to execute this text file instead of entering the commands. This is known as shell script. it is series of command written in plain text file. it is just like batch file is MS-DOS but have more power than the MS DOS batch file.
Why to Write Shell Script
1) It can take input from user, file and output them on screen.
2) Useful to create our own commands
3) Save lots of time.
4) To automate some task of day today life.
5) System Administration part can be also automated.
First “Hello World”
Saving and executing first “Hello World”
1) In this tutorial we are going to get started with shell programming, how to write script, execute them etc. We will get started with writing small shell script, that will print “Hello world” on screen.
2) To write it you can use any editor supported like vi or mcedit.
3) I will use vi editor: To open a new file in vi edit you can use the command vi followed by the script name that you would want to save your file as.
4) Note that shell scripts have an extension of .sh vi hello.sh
#My first shell script
echo “Hello World”
1) To save this file, press wq and exit
2) Before you can set execute the shell script, you need to set execute permission for your script as follows:
chmod permission your-script-name
$ chmod +x your-script-name
$ chmod 755 your-script-name
Note: This will set read write execute(7) permission for owner, for group and other permission is read and execute only(5).
chmod 755 hello.sh
There are couple of ways to execute the shell script.
$ bash hello.sh
$ sh hello.sh
NOTE:- In the last syntax ./ means current directory, But only . (dot) means execute given command file in current shell without starting the new copy of shell, The syntax for . (dot) command is as follows
$ . num_var
Let us analyses the script we wrote. You can re open the script vi hello.sh (Start vi editor)
In the script,
# My first shell script
# followed by any text is considered as comment. Comment gives more information about script, logical explanation about it.
echo “Hello World”
To print message or value of variables on screen, we use echo command, general form of echo command is as follows
I hope that you understand my post. if you like this post then share my post, and comment on my post if you have any suggestion or Queries related to computer. Thank you!