Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev
Chapter 7: awk Revisited
Next

if condition in awk

General syntax of if condition is as follows:
Syntx:
if ( condition )
{
       Statement 1
       Statement 2
       Statement N
       if condition is TRUE
}
else
{
       Statement 1
       Statement 2
       Statement N
      if condition is FALSE
}

Above if syntax is selfexplontary, now lets move to next awk program


$ awk > math2
BEGIN {
  myprompt = "(To Stop press CTRL+D) > "
  printf "Welcome to MyAddtion calculation awk program v0.1\n"
  printf "%s" ,myprompt
}

{
no1 = $1
op = $2
no2 = $3
ans = 0

if ( op == "+" )
{
     ans = $1 + $3
     printf "%d %c %d = %d\n" ,no1,op,no2,ans
     printf "%s" ,myprompt
 }
 else
 {
     printf "Opps!Error I only know how to add.\nSyntax: number1 + number2\n"
     printf "%s" ,myprompt
  }
}

END {
    printf "\nGoodbuy %s\n" , ENVIRON["USER"]
}

Run it as follows (Give input as 5 + 2 and 3 - 1 which is shown in bold words)
$awk -f math2
Welcome to MyAddtion calculation awk program v0.1
(To Stop press CTRL+D) > 5 + 2
5 + 2 = 7
(To Stop press CTRL+D) > 3 - 1
Opps!Error I only know how to add.
Syntax: number1 + number2
(To Stop press CTRL+D) >
Goodbuy vivek

In the above program various, new concept are introduce so lets try to understand them step by step

BEGIN {Start of BEGIN Pattern
myprompt = "(To Stop press CTRL+D) > "Define user define variable
printf "Welcome to MyAddtion calculation awk program v0.1\n"
printf "%s" ,myprompt
Print welcome message and value of myprompt variable.
}End of BEGIN Pattern
{Now start to process input
no1 = $1
op  = $2
no2 = $3
ans = 0   
Assign first, second, third, variables value to no1, op, no2 variables respectively
if ( op == "+" )
{
 ans = no1 + no2
 printf "%d %c %d = %d\n" ,no1,op,no2,ans
 printf "%s" ,myprompt 
}      
else
{
 printf "Opps!Error I only know how to add.\nSyntax:number1+ number2\n"
 printf "%s" ,myprompt
}      
If command is used for decision making in awk program. Here if value of variable op is "+" then addition is done and result is printed on screen, else error message is shown on screen.
}Stop all inputted lines are process. 
END {
  printf "\nGoodbuy %s\n" , ENVIRON["USER"] 
}
END patterns start here.
Which says currently log on user Goodbuy.

ENVIRON is the one of the predefined system variable that is array. Array is made up of different element. ENVIRON array is also made of elements. It allows you to access system variable (or variable in your environment). Give set command at shell prompt to see list of your environment variable. You can use variable name to reference any element in this array. For e.g. If you want to print your home directory you can write printf as follows:
printf "%s is my sweet home", ENVIRON["HOME"]


Prev
Home
Next
Use of Format Specification Code
Up
Loops in awk