1

I need help figuring out why my case statement is not properly evaluating my first 2 values (visitor_id, updated) in my list. Here's the code:

#!/usr/local/bin/bash
file="mydatasample.out";
linecount=$(wc -l <"$file" | awk '{ print $1 }')
counter=1
while IFS='' read -r column; do
  case column in
    visitor_id)
       echo "isnull($column|| '[|]' ||";;
       updated)
       echo "isnull($column::text || '[|]' ||";;
             *)
       echo "isnull($column::text,'[null!]') || '[|]' ||";;
  esac
  if [ "$counter" -eq "$linecount" ]; then
      echo "isnull($column::text,'[null!]')) as md5sum"
  fi
  ((counter++))
done <"$file"

=mydatasample.out=

visitor_id
updated
visitor_1_key
visitor_1_value
visitor_2_key
visitor_2_value

Getting:

isnull(visitor_id::text,'[null!]') || '[|]' ||
isnull(updated::text,'[null!]') || '[|]' ||
isnull(visitor_1_key::text,'[null!]') || '[|]' ||
isnull(visitor_1_value::text,'[null!]') || '[|]' ||
isnull(visitor_2_key::text,'[null!]') || '[|]' ||
isnull(visitor_2_value::text,'[null!]')) as md5sum

Expecting:

isnull(visitor_id|| '[|]' ||
isnull(updated::::text || '[|]' ||
isnull(visitor_1_key::text,'[null!]') || '[|]' ||
isnull(visitor_1_value::text,'[null!]') || '[|]' ||
isnull(visitor_2_key::text,'[null!]') || '[|]' ||
isnull(visitor_2_value::text,'[null!]')) as md5sum

So, its the first (2) values that I want to evaluate, but so far cannot. Thanks for your help.

6
  • did you mean case "$column" in ... ? Commented Jan 26, 2018 at 21:09
  • could be..is it as simple as that? i will try. thanks Commented Jan 26, 2018 at 21:10
  • 1
    shellcheck autodetects this and other common problems. You can consider installing it in your editor. Commented Jan 26, 2018 at 21:14
  • 1
    Another suggestion: rather than all the linecount and counter stuff, just put the echo "... as md5sum" command after the loop, so it runs with the last value of $column. Commented Jan 27, 2018 at 6:00
  • 1
    @noober: Actually, I take it back; that wouldn't work. read sets column to each line as it's read, but after the last line there's a final read that reads the end-of-file and sets column to null. But if you add lastcolumn=$column inside the loop, then after the loop that'll have the last actual column left in the column variable, and you can use that to print the "... as md5sum". Commented Jan 30, 2018 at 22:02

1 Answer 1

3

case, unlike for, doesn't interpret column as $column (because for needs to know the name of the variable to assign to, while case needs to know the value to compare it).

You probably wanted

case "$column" in
Sign up to request clarification or add additional context in comments.

1 Comment

yay! thank you very much. quick fix for sure. appreciate the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.