Monday, 17 September 2012

Beginner's Introduction to Shell Script: PART 2

Beginner's Introduction to Shell Script: PART 1

Beginner's Introduction to Shell Script:PART 2
1. Beyond the Basics

1.1. Internal Variables:


Builtin variables:





variables affecting bash script behavior

$BASH
The path to the Bash binary itself

bash$ echo $BASH
/bin/bash

$BASH_ENV
An environmental variable pointing to a Bash startup file to be read when a script is invoked

$BASH_SUBSHELL
A variable indicating the subshell level. This is a new addition to Bash, version 3.
See Example 21-1 for usage.

$BASHPID
Process ID of the current instance of Bash. This is not the same as the $$ variable, but it often gives the same result.

bash4$ echo $$
11015


bash4$ echo $BASHPID
11015


bash4$ ps ax | grep bash4
11015 pts/2    R      0:00 bash4
       



$BASH_VERSION
The version of Bash installed on the system

bash$ echo $BASH_VERSION
3.2.25(1)-release

$HOME
Home directory of the user, usually /home/username

$HOSTNAME
The hostname command assigns the system host name at bootup in an init script. However, the gethostname() function sets the Bash internal variable$HOSTNAME.

$HOSTTYPE
host type
Like $MACHTYPE, identifies the system hardware.

bash$ echo $HOSTTYPE
i686

$MACHTYPE
machine type
Identifies the system hardware.

bash$ echo $MACHTYPE
i686

$OSTYPE
operating system type

bash$ echo $OSTYPE
linux

$PPID

The $PPID of a process is the process ID (pid) of its parent process. [2]
Compare this with the pidof command.(pidof -- find the process ID of a running program.)

$PROMPT_COMMAND
A variable holding a command to be executed just before the primary prompt, $PS1 is to be displayed.

$PS1
This is the main prompt, seen at the command-line.

$PS2
The secondary prompt, seen when additional input is expected. It displays as ">".

$PS3
The tertiary prompt, displayed in a select loop.

$PS4
The quartenary prompt, shown at the beginning of each line of output when invoking a script with the -x option. It displays as "+".

$PWD
Working directory (directory you are in at the time)
This is the analog to the pwd builtin command.

$UID
User ID number

The variables $ENV$LOGNAME$MAIL$TERM$USER, and $USERNAME are not Bash builtins


These are, however, often set asenvironmental variables in one of the Bash startup files. $SHELL, the name of the user's login shell, may be set from /etc/passwd or in an "init" script, and it is likewise not a Bash builtin.

sankar@new-host ~]$ echo $LOGNAME
sankar
[sankar@new-host ~]$ echo $SHELL
/bin/bash
[sankar@new-host ~]$ echo $TERM
xterm


Positional Parameters

$0$1$2, etc.
Positional parameters, passed from command line to script, passed to a function, or set to a variable..
$#
Number of command-line arguments [4] or positional parameters..
$*
All of the positional parameters, seen as a single word

Note"$*" must be quoted.
$@
Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

NoteOf course, "$@" should be quoted.

$?







Exit status of a command, function, or the script itself..

$$
Process ID (PID) of the script itself. The $$ variable often finds use in scripts to construct "unique" temp file names . This is usually simpler than invoking mktemp.

1.2. Typing variables: declare or typeset

 permit modifying the properties of variables. This is a very weak form of the typing.

declare/typeset options:


 -r readonly




(declare -r var1 works the same as readonly var1)

     declare -r var1=1
     echo "var1 = $var1"   # var1 = 1

  
 -i integer

declare -i number
# The script will treat subsequent occurrences of "number" as an integer.  

number=3
echo "Number = $number"     # Number = 3

-a array

declare -a indices

-f function(s)

    declare -f function_name


-x export









declare -x var3

This declares a variable as available for exporting outside the environment of the script itself.

-x var=$value

declare -x var3=373

NOTE:The declare command can be helpful in identifying variables, environmental..



bash$ declare | grep HOME
HOME=/home/bozo

bash$ zzy=68
bash$ declare | grep zzy
zzy=68


1.3. $RANDOM: generate random integer

   $RANDOM is an internal Bash function (not a constant) that returns a pseudo random integer in the range 0 - 32767. 

1.4. Manipulating Variables

Bash supports a surprising number of string manipulation operations.

2. Loops and Branches

2.1. Loops

for loops This is the basic looping construct.

Syntax: 
for arg  in [list] do   command(s)...  done
----------------
If do is on same line as for..
for arg  in [list] ; do 
Note: During each pass through the loop, arg takes on the value of each successive variable in the list.

The argument list may contain wild cards.


Example  Simple for loops
1. $vim sfloop.sh






#!/bin/bash
# Listing the planets.

for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
do
  echo $planet  # Each planet on a separate line.
done


:wq


[sankar@new-host loops]$ chmod +x sfloop.sh
[sankar@new-host loops]$ ./sfloop.sh
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto

Each [list] element may contain multiple parameters. This is useful when processing parameters in groups.

2. Listing all users on the system.

$vim listallusers.sh

#!/bin/bash
# userlist.sh

PASSWORD_FILE=/etc/passwd
n=1           # User number

for name in $(awk 'BEGIN{FS=":"}{print $1}' < "$PASSWORD_FILE" )
# Field separator = :    ^^^^^^
# Print first field              ^^^^^^^^
# Get input from password file               ^^^^^^
do
  echo "USER #$n = $name"
  let "n += 1"
done  


# USER #1 = root
# USER #2 = bin
# USER #3 = daemon
# ...
# USER #30 = bozo

exit $?

#  Discussion:
#  ----------
#How is it that an ordinary user, or a script run by same,
#+ can read /etc/passwd? (Hint: Check the /etc/passwd file permissions.)
#  Isn't this a security hole? Why or why not?

:wq

2.3. Testing and Branching

case "$variable" in  

  "$condition1" ) 
 command... 
 ;;  
  "$condition2" ) 
 command... 
 ;;  

esac



Note
  • Quoting the variables is not mandatory, since word splitting does not take place.
  • Each test line ends with a right paren ).
  • Each condition block ends with a double semicolon ;;.
  • If a condition tests true, then the associated commands execute and the case block terminates.
  • The entire case block ends with an esac (case spelled backwards).
  • eg: $vim machinetype.sh
    case $( arch ) in   # $( arch ) returns machine architecture.
      ( i386 ) echo "80386-based machine";;
    # ^      ^
      ( i486 ) echo "80486-based machine";;
      ( i586 ) echo "Pentium-based machine";;
      ( i686 ) echo "Pentium2+-based machine";;
      (    * ) echo "Other type of machine";;
    esac
    
    
    :wq
    
    
    [sankar@new-host loops]$ ./machinetype.sh
    Pentium2+-based machine
    
    
    
    
    3. Arithmetic Expansion
    Arithmetic expansion provides a powerful tool for performing (integer) arithmetic operations in scripts. 
    
    
    z=`expr $z + 3`          # The 'expr' command performs the expansion.
    
    
    Arithmetic expansion with double parentheses, and using let
    
    
    z=$(($z+3))
    z=$((z+3))                                  #  Also correct.
                                                #  Within double parentheses,
                                                #+ parameter dereferencing
                                                #+ is optional.
    
    # $((EXPRESSION)) is arithmetic expansion.  #  Not to be confused with
                                                #+ command substitution.
    
    
    
    # You may also use operations within double parentheses without assignment.
    
      n=0
      echo "n = $n"                             # n = 0
    
      (( n += 1 ))                              # Increment.
    # (( $n += 1 )) is incorrect!
      echo "n = $n"                             # n = 1
    
    
    let z=z+3
    let "z += 3"  #  Quotes permit the use of spaces in variable assignment.
                  #  The 'let' operator actually performs arithmetic evaluation,
                  #+ rather than expansion.
    
    
    
    
    
    
    
    
    
    
    
    Beginner's Introduction to Shell Script: PART 3
    Beginner's Introduction to Shell Script: PART 4
    Beginner's Introduction to Shell Script: PART 5
    Beginner's Introduction to Shell Script: PART 6


No comments:

Post a Comment