Basics of Shell Script
When we want to execute a group of commands, then they should be stored in a file, and the file itself executed as a shell program or shell script. We use a .sh extension for all shell scripts.
Every Shell script begins with special interpreter line like- #!/bin/sh
OR #!/bin/ksh
OR #!/bin/bash
This interpreter line specifies, which shell (Bourne/Korn/Bash) user prefer to execute the shell script, and it may or may not be same as a user login shell.
Examples:
1. The following script displays the system current date and current months calendar.
#!/bin/sh #Sample Shell Script – sample.sh echo "Today's Date: `date`" echo "This Month's Calender:" cal
Execution and Output:
Steps to run the script:
1. First, we need to change the permissions of the script to be executed using chmod.
2. Then using sh command the script is executed.
$ chmod 777 sample.sh #Make Script Executable $ sh sample.sh #Execute Script – sample.sh Today's Date: Sun Jan 13 15:40:13 IST 2013 This Month's Calender: January 2013 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
2. Making the script interactive by reading data from standard input such as a keyboard.
#!/bin/sh #Sample Shell Script - simple.sh echo "Enter Your First Name:" read fname echo "Enter Your Last Name:" read lname echo "Your First Name is: $fname" echo " Your Last Name is: $lname"
Execution and Output:
$ chmod 777 simple.sh $ sh simple.sh Enter Your First Name: Rahul Enter Your Last Name: Dravid Your First Name is: Rahul Your Last Name is: Dravi
Using the command line arguments
Shell script also accepts arguments from the command line. It makes the shell script to run non-interactively and be used with redirection and pipelines. When arguments are specified with a shell script, they are assigned to positional parameters. The shell uses the following parameters to handle command line arguments –
Shell parameter | Significance |
>$# | Number of arguments specified in the command line |
$0 | Name of the executed command |
$1, $2, … | Positional parameters representing command line arguments |
>$* | Complete set of positional parameters as a single string |
$@ | Each quoted string is treated as a separate argument, same as $* |
3. Shell Script to demonstrate command line arguments
#!/bin/sh #Shell Script to demonstrate command line arguments - sample.sh echo "The Script Name is: $0" echo "Number of arguments specified is: $#" echo "The arguments are: $*" echo "First Argument is: $1" echo "Second Argument is: $2" echo "Third Argument is: $3" echo "Fourth Argument is: $4" echo "The arguments are: $@"
Execution and Output:
$ sh sample.sh welcome to hit nidasoshi [Enter] The Script Name is: sample.sh Number of arguments specified is: 4 The arguments are: Welcome to VTU Belagavi First Argument is: Welcome Second Argument is: to Third Argument is: VTU Fourth Argument is: Belagavi The arguments are: Welcome to VTU Belagavi