1
#!/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.

3
  • input is CLI. Paste that in terminal, hit Enter: everything you tipe into stdin will be fed to the script when hitting Enter again. Commented May 12, 2020 at 13:21
  • 1
    If you're doing nothing but calling awk in your script, you might as well start it with a #!/usr/bin/awk -f (adjust for correct location of awk) shebang line and drop the single quotes; see gnu.org/software/gawk/manual/gawk.html#Executable-Scripts Commented May 12, 2020 at 13:59
  • Awk will continue reading input and looping until end-of-file (ctrl-d in bash). Commented May 12, 2020 at 14:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why does the program takes input from stdin and how is the program reading it? This might seem like a weird question but i want to understand the workings of the code.
@FNF I've added the why. How is a deeper and totally different question that would be out of place in the answer. I refer you to How to signal the end of stdin input and How does a program detect the end of stdin input?, they may be illuminating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.