Reputation: 47
#!/bin/bash -f
awk '
BEGIN {
print "type a number";
}
{
printf "The square of %d is %d\n", $1, $1*$1;
#print "The square of ", $1, " is ", $1*$1;
print "type another number\n";
}
END {
print "Done"
}'
Can anyone explain how this program takes input? I tried searching on the web but in vain. Grateful for any explanation given. Thanks.
Upvotes: 1
Views: 721
Reputation: 4004
The program takes input from stdin. So, after making it executable with chmod +x scriptname
, you can either start it with ./scriptname
and answer to each prompt, or redirect a file's content to stdin. For example, suppose this is numbers.txt
:
4
7
1
Then execute the script this way:
$ ./scriptname < numbers.txt
type a number
The square of 4 is 16
type another number
The square of 7 is 49
type another number
The square of 1 is 1
type another number
Done
Why does that awk script read standard input? According to awk POSIX specification, section STDIN:
The standard input shall be used only if no file operands are specified, or if a file operand is '-', or if a progfile option-argument is '-';
Notice that awk was provided no file operand, so stdin is used.
Upvotes: 2