Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Why do I get only "cat" when I run

awk 'BEGIN {
  animal[three] = "hen"
  animal[two]   = "dog"
  animal[one]   = "cat"
  for (var in animal) {
    print animal[var]


Shouldn't it print "hen", "dog" and "cat"?

share|improve this question
Missing a ' at the end of the code. – fedorqui Apr 10 '14 at 8:28

Indices to awk arrays can either be numeric (as in a traditional array) or strings (an associative array). So you can either do

animal[1] = "cat"


animal["one"] = cat

However, if you do

animal[one] = cat

awk will try to find a variable called 'one', fail, and effectively do this:

animal[""] = cat

So in your program, all three animals are assigned to animal[""], so you end up with only one element in your array.

If you put one, two and three in quotes, your code will work as you expect.

share|improve this answer
Good one! You can also indicate by printing print animal[var], "-"var"-". var is empty, - to show where it starts and where it ends. – fedorqui Apr 10 '14 at 8:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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