Simple Example of a Positional Parameter

For example, if a shell program mypgm expects two parameterssuch as a first name and a last nameyou can invoke the shell program with only one parameter, the first name. However, you cannot invoke it with only the second parameter, the last name.

Here is a shell program called mypgm1, which takes only one parameter (a name) and displays it on the screen:

then echo "Name not provided" else echo "Your name is "$1

If you execute mypgm1, as follows,

$ bash mypgm1

you get the following output:

Name not provided

However, if you execute mypgmi, as follows,

$ bash mypgmi Sanjiv you get the following output:

Your name is Sanjiv

The shell program mypgm1 also illustrates another aspect of shell programming: the builtin variables provided to the shell by the Linux kernel. In mypgm1, the built-in variable $# provides the number of positional parameters passed to the shell program. You learn more about working with built-in variables in the next major section of this chapter.

Was this article helpful?

0 0

Post a comment