1

I have the following working function in my bash script:

addMD5SUM()
{
file=$COLS2
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"
}

Where $COL2 is a single filename:

COLS2="myoutputfile2.out"

Contents of this file would be something like:

visitor_id
updated
visitor_list_1
visitor_list_2
visitor_list_3
visitor_list_4
visitor_list_5

Other files would be similar: (i.e.)

visitor_id
updated
visitor_list_6
visitor_list_7
visitor_list_8
visitor_list_9
visitor_list_10

Now, I need to alter this function so that I have the option to have it work with either one of these files:

export COLS1="myoutputfile1.out"
export COLS2="myoutputfile2.out"
export COLS3="myoutputfile3.out"
export COLS4="myoutputfile4.out"

How would you do this? Would you do this as an if-statement? What is the best and proper way to do handle this?

2
  • Please post the example sample Input_file and expected sample output too in your post. Commented Jan 26, 2018 at 6:48
  • 1
    linecount=$(wc -l <"$file") Commented Jan 26, 2018 at 7:49

3 Answers 3

2

Send the COLSn as a parameter to the function

addMD5SUM()
{
  file="$1"
  ...
}

then

addMD5SUM $COLS1
addMD5SUM $COLS2
...
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! thank you. That makes sense and was simple enough.
0

Use the evil eval to let Bash parse the variable for an extra pass.

export COLS1="myoutputfile1.out"
export COLS2="myoutputfile2.out"
export COLS3="myoutputfile3.out"
export COLS4="myoutputfile4.out"

addMD5SUM()
{
eval file=\$$1
...

And call the new function like

addMD5SUM COLS1
addMD5SUM COLS2
addMD5SUM COLS3
addMD5SUM COLS4

Comments

0

As said in the accepted answer, you can send an argument to the function but user supplied arguments shouldn't be trusted.

Since your files have a format, you could do something like below

file=${1:-0} # If the argument 1 is not present, assign zero to file
! [[ "${file}" =~ myoutputfile[0-9]+.out ]] || ! [ -f "${file}" ] &&
echo "Invalid parameter" && exit 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.