Sunday, 25 September 2016

Unix | shell variables

Shell variables

The shell support variables that are useful both in command line and shell programming .you will deal with three basic variables.

   1.    Positional variables
   2.    Special variables
   3.    Named variables

1) positional variables : on several occasions, you may require the shell programs to accept an arguments from the command line itself . To facilitate this process, positional parameters are provided. Using these parameters you can pass up to nine arguments to the shell programmers from the command line itself. These parameters may be file name, pathname, username, and so on. These parameters are invoked like normal shell variables with a preceding ‘$’sign as $1,$2,-----------------$q. the first arguments specified after the shell program will be assigned to $1, the second to $2 and so on.
Example: 
$ cat>name
 echo ”your first name is” :$1
 echo ”your middle name is” :$2
 echo ”your last name is” :$3
   (Ctrl + d)
    $

2) special variables  : there  are two special parameters that are of special interest to us. They also pertain to arguments specified at the command line.
 
 $ # this parameter returns the number of arguments that are specified on the command line.
Example: 
$ cat>how-many-arguments
Echo ”the number of arguments specified is” :$#
(ctrl + )
$

$ How-many-arguments: just testing this programs.
The number of arguments specified is: 4

$* this parameter, when referenced within the shell programs ,retuen a string with all the parameters with which the shell programs was invoked
Example: 
$ cat>display-args
 Echo “ the args are”: $*
  (Ctrl + d)
    $
$ display args hello word I am except in Unix
The args are : hello word I am except in Unix

3) Named variables: a named variable is a user defined variable that can be assigned the value of named variable can be retrieved by preceding the variable name with a”$” sign
Exampl:
 $myvar=hello
 $ echo $ myvar
   Hello

The first character of a variable name must be a letter or  an underscore. The rest of the name may be composed of letter, digit and underscore combined










No comments:

Post a Comment