8

Consider this script:

function alfa(bravo, charlie) {
  if (charlie)
    return "charlie good"
  else {
    return "charlie bad"
  }
}
BEGIN {
  print alfa(1, 1)
  print alfa(1, 0)
  print alfa(1, "")
  print alfa(1)
}

Result:

charlie good
charlie bad
charlie bad
charlie bad

Does Awk have a way to tell when an argument has not been provided?

2 Answers 2

6

Yes, you can do this:

function alfa(bravo, charlie) {  
  if (charlie) {
    return "charlie good"
  }
  if (charlie == 0 && charlie == "") {
    return "charlie not provided"
  }
  if (!charlie && charlie != 0) {
    return "charlie null"
  }
  if (!charlie && charlie != "") {
    return "charlie 0"
  }
}

Result:

charlie good
charlie 0
charlie null
charlie not provided
6

awk doesn't have a builtin way to check variable had been initialized. You must do it yourself:

function alfa(bravo, charlie) {
  if (charlie == 0 && !length(charlie))
    return "charlie bad"
  else {
    return "charlie good"
  }
}
BEGIN {
  print alfa(1, 1)
  print alfa(1, 0)
  print alfa(1, "")
  print alfa(1)
}

The general way:

var == 0 && !length(var)

An uninitialized variable and 0 causes var == 0 to be evaluated to true, !length(var) excludes the case when var = 0.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.