Command Line Arguments in Unix Shell Script with Example

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 7, 2024

Overview of Unix Command Line Arguments:

The Unix shell is used to run commands, and it allows users to pass run time arguments to these commands.

These arguments, also known as command line parameters, that allows the users to either control the flow of the command or to specify the input data for the command. 

Unix Video #22:

In this tutorial, we will understand how to work with command line parameters.

While running a command, the user can pass a variable number of parameters in the command line.

Within the command script, the passed parameters are accessible using ‘positional parameters’.  These range from $0 to $9, where $0 refers to the name of the command itself, and $1 to $9 are the first through to the ninth parameter, depending on how many parameters were actually passed.

Example:

$ sh hello how to do you do

Here $0 would be assigned sh

$1 would be assigned hello

$2 would be assigned how

And so on …

We will now look at some additional commands to process these parameters.

#1) set

This command can be used to set the values of the positional parameters on the command line.

Example:

$ set how do you do
$ echo $1 $2
how do

Here, “how” was assigned to $1 and “do” was assigned to $2 and so on.

#2) shift

This command is used to shift the position of the positional parameters. i.e. $2 will be shifted to $1 all the way to the tenth parameter being shifted to $9. Note that if in case there are more than 9 parameters, this mechanism can be used to read beyond the 9th.

Example:

$ set hello good morning how do you do welcome to Unix tutorial.

Here, ‘hello’ is assigned to $1, ‘good’ to $2 and so on to ‘to’ being assigned to $9.  Now the shift command can be used to shift the parameters ‘N’ places.

Example:

$ shift 2
$ echo $1

Now $1 will be ‘morning’ and so on to $8 being ‘unix’ and $9 being ‘tutorial’.

Check our upcoming tutorial to know more about Processes in Unix.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

Leave a Comment