getDateFormat() {
  year=`echo $1 | awk -F"-" '{print $2}'`
  mm=`echo $1 | awk -F"-" '{print $3}'`
  for x in January February march april may july jun august September October November December
    if [ $mm -eq $ii ]; then
    ii=`expr $ii + 1`
  mday=`echo $1 | awk -F"_" '{print $1}' | awk -F"-" '{print $4}'`

I would like to know What does the above function do?

$ awk '$2 == "1" { print $0 }' cols.txt 

Where the match occurs, print the entire line. But what this command returns

echo $1 | awk -F"-" '{print $2}'

$ii - What is this?

echo $ii 

It didn't print anything.

  • 5
    One cannot explain this abomination of code. From uninitialized variables ($ii used in a test) to inconsistent spelling and capitalization of the months, to an undocumented and clearly uncommon input requirement.
    – KevinO
    Jun 16 '17 at 15:27

$1 is the first positional parameter, i.e. argument to the function. awk -F- sets awks field separator to a dash, and print $2 prints the second field. So from aa-bb-cc, you'd get bb.

Presumably the function expects to be called as getDateFormat something-2017-06 which looks odd, but the year is picked from the second dash-separated field.

$ii would refer to a variable, but it's not set before the test if [ $mm -eq $ii ]; so the test sees [ 123 -eq ] (with 123 probably some number picked from $1). That causes an error since the operator -eq is missing the other operand.

  • ii is undefined on the first iteration, but that's semantically zero; on subsequent iterations, it gets incremented. I don't think the logic is entirely correct, but with a few fixes, the loop would convert -- horribly clumsily -- from a month name to a month number. (Notice also how the month names use erratic capitalization and abbreviation conventions, and how July is incorrectly listed before June.)
    – tripleee
    Jun 16 '17 at 15:43
  • I guess with ii=1 instead of i=1 it would superficially work for many month names.
    – tripleee
    Jun 16 '17 at 15:47
  • mm is set before the loop, apparently to the month name.
    – tripleee
    Jun 16 '17 at 15:47
  • @tripleee, without changing from i=1 to ii=1, I get an error in bash on the first loop, so I think it needs to be set prior to the first loop iteration as you subsequently noted.
    – KevinO
    Jun 16 '17 at 15:56
  • @tripleee, sorry, my bad on the mm. But since $ii is unquoted, it resolves to nothing, so that still doesn't work... And even when quoted, I think the empty string would give an error from -eq.
    – ilkkachu
    Jun 16 '17 at 16: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.