Featured Post

Taking inputs from user in a script

Here we will see how to take input from user in a script with the help of read command. #!/bin/bash Lets try multiplication of two numbers which the user enters. What read does is ? It takes values by user on stdin. It prompt the user to input any value on stdin. -p is used to display a prompt. read -p "First number:" value1 This will give a prompt as " First number " and store the value in variable " value1 " echo Will display a blank line. read -p "Second number:" value2 This will give a prompt as " Second number " and store the value in variable " value2 " echo Will display a blank line. read -sn1 -p "Press any key to see the answer..." Just to make it bit more interactive lets add one more thing. -s means silent mode that is if any value is pressed it will not be displayed on the screen like as in the password. -nX means how many characters. X here is one that is any

What is a Shell Script?

"Shell Script is series of command written in plain text file. It is same as a batch file which is there in MS operating system".

Basically it contains a sequence of commands for a UNIX-based operating system. It is called a script because it combines all the commands into a single file and we need not to execute each and every command its just the script which we need to execute.

A shell script is usually created for command sequences for which a user has a repeated need and the script can be executed simply by writing the script name with its syntax.

Lets write a simple script to display user by which you are logged in? date and time? your present working directory?


  • For user we can use "whoami" command.
  • For date and time we can use "date" command.
  • For present working directory we can use "pwd" command.
  • For getting this printed on standard output we can use "echo" command.

Lets say we wrote a file as test.sh as: 

[root@sunny-workstation Desktop]# cat test.sh 
#!/bin/bash
echo -e "Date and time is: `date` \n"
echo -e "Your username is: `whoami` \n"
echo -e "Your current directory is: `pwd` \n"
[root@sunny-workstation Desktop]#

Lets get this file executed, (PS: there are various ways to get a script file executed and its components like shebang etc we will touch-base on this later):

[root@sunny-workstation Desktop]# ./test.sh
Date and time is: Wed Apr 29 07:29:47 CEST 2015 

Your username is: root 

Your current directory is: /home/sunny/Desktop 

[root@sunny-workstation Desktop]#

Comments

Popular posts from this blog

Merging of various commands

Positional parameters in Bash scripting

Sourcing a variable