-2

Awk has builtin functions which are operating on numbers and strings. That is exactly what a programming language does.

That makes me wonder if I can use awk to perform some number or string operations using awk, without specifying a file as input? Can awk work without input from file or stdin?

For example, I would like awk to evaluate 1+2, and hardcode the "input" 1 and 2 in a awk program. Okay, I answer myself:

$ awk "BEGIN{print 1+2}"
3

But I am surprised that awk doesn't wait for input from stdin since I don't specify an input file. Why not?

Thanks.

2

This is by design. It's documented in (at least) the GNU man page for awk

If the program consists entirely of BEGIN blocks, then execution terminates, else an input stream is opened and execution continues.

From POSIX:

If an awk program consists of only actions with the pattern BEGIN, and the BEGIN action contains no getline function, awk shall exit without reading its input when the last statement in the last BEGIN action is executed.

  • Thanks. Is this the only case when awk doesn't expect an input? Or I should ask how you would write an awk program if you don't want awk to expect an input? – Tim Nov 14 '18 at 23:15
  • @Tim This is the only case. – Kusalananda Nov 14 '18 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.