This tutorial will show you an example on using arguments to a unix shell script or programming. Here we will create a shell script file for showing the example.
The advantage of using urguments is you can pass the value dynamically as per the requirements. You don’t need to edit the shell script file everytime you pass the different value for the shell script.
Knowledge of Unix
Creating Shell Script
Now open a Unix terminal and create a shell script file called
You can simply execute the command
vi name.sh in the terminal.
The vi editor comes by default with almost every Unix terminal.
.sh is the extension of the shell script file.
Write the below content in name.sh file.
echo "My first name is $1" echo "My last name is $2" echo "Total number of arguments is $#"
In the above program you see how we are indicating command line arguments.
$2 are the command line arguments passed along with the file name from Unix command. The third line shows the total count of command line arguments passed to the program using the syntax
Testing the Shell Script
Run the script name.sh using the following command from the Unix terminal.
$ ./name.sh Soumitra Roy
By executing the above command you will see the following output on the terminal.
My first name is Soumitra My last name is Roy Total number of arguments is 2
We are assuming that the shell script file name.sh exists in the current directory.
Here we are executing the shell script file from current directory using command
./name.sh and we have passed values for two arguments –
Roy. And here in the output you see how the argument’s value is displayed.
So you have got an idea on using arguments to a Unix shell script in the above example.
Thanks for reading.