Positional Parameters

The first word on command line (example: ls), is name of the command to be executed. Everything else on command line is taken as arguments to this command.

Command Line Processing

Now try following command (assumes that the file file1 not exist on your disk)

ls file1

It will print message something like -

file1: No such file or directory

Well as it turns out ls command was the name of an actual command and shell executed this command when given the command. Now it creates one question What are commands? What happened when you type ls file1. The first word on command line, ls, is name of the command to be executed. Everything else on command line is taken as arguments to this command.

Example:

tail +10 myf

Here the name of command is tail, and the arguments are +10 and myf.

Now try to determine command and arguments from following commands:

ls foo
cp y y.bak
mv y.bak y.okay
tail -10 myf
mail raj
sort -r -n myf
date
clear

CLI Requirements

Let’s take rm command, which is used to remove file, But which file you want to remove and how you will, you tell this to rm command (Even rm command does not ask you name of file that would like to remove).

So what we do is we write as command as follows

Syntax:

rm {file-name}

Here rm is command and file-name is file which you would like to remove. This way you tell to rm command which file you would like to remove. So we are doing one way communication with our command by specifying file-name. Also, you can pass command line arguments to your script to make it more users friendly. But how we address or access command line argument in our script.

Let’s take ls command

ls -a /*

This command has 2 command line argument -a and /* is another.

For shell script,

myshell foo bar
  1. myshell is the script name
  2. foo is the first command line argument
  3. bar is the second comman line argument

In shell script, if we wish to refer this command line argument,

  1. myshell will be $0
  2. foo will be $1
  3. bar will be $2

Here $# will be 2 (Since foo and bar only two Arguments)

Note

At a time such 9 arguments can be used from $0..$9, You can also refer all of them by using $* (which expand to $0,$1,$2...$9)

Now try to write following for commands, Shell Script Name $0, No. of arguments (i.e. $#), and actual argument (i.e. $1,$2 etc)

Subscribe For More Content