Dynamic variable assignment

#!/bin/sh

if [ $# -ne 1 ]
then
  echo "Insufficient number of arguments ">> error".log" ;
  echo "Please check error log for more details";
  exit 1 ;
else
  file_name=$1".csv";
fi ;

in_par_number=`head -n1 $file_name | sed 's/[^,]//g' | wc -c`

read -a arr <<< `head -n1 $file_name | sed 's/[^,]/ /g'`

for e in ${arr[@]}; 
do
    echo $e
done

I would like to do variable assignment of all column values in header row, so that i can validate each and every column value later using this variables.

I don't quite understand your intention, but there's usually a better way to do things than setting arbitrary variable names. Arrays, for example. Keep an array of the acceptable values for each column.

Shell does not need the help of the external programs head and sed to read and tokenize one line of a file.

IFS="," read -a ARR <inputfile.csv
echo Columns count is ${#ARR[@]}

I have changed code as per your suggession however i am getting following error.

$ ./test.ksh Filename
./test.ksh[12]: read: bad option(s)
Columns are 0

OLD:

in_par_number=`head -n1 $file_name | sed 's/[^,]//g' | wc -c`

read -a arr <<< `head -n1 $file_name | sed 's/[^,]/ /g'`

for e in ${arr[@]}; 
do
    echo $e
done

NEW:

IFS="," read -a ARR <$file_name
echo Columns are ${#ARR[@]}

-a only works in bash shell, not ksh. I'm not certain why you didn't encounter this error yourself, as your own code used -a too.

I still don't understand your intention for "dynamic variables" in any case, can you explain?

KSH uses -A instead:

IFS="," read -A ARR <filename.csv

I want to assign columns in first row of a csv file into dynamic variables in KSH.

---------- Post updated at 10:38 PM ---------- Previous update was at 10:31 PM ----------

example if first row of csv file is Jay,1000,Doshi,1234
code should assign

var1=Jay
var2=1000
var3=Doshi
var4=1234

Oh. That's the exact opposite of dynamic, when you know the variable names you want already.

exec 5<file.csv # Open file into FD 5

# Read first line
IFS="," read VAR1 VAR2 VAR3 VAR4 <&5
# Read second line
IFS="," read VAR1 VAR2 VAR3 VAR4 <&5
# etc

# A loop 
while IFS="," read VAR1 VAR2 VAR3 VAR4 <&5
do
        echo "column 1 is $VAR1"
done

# close file
exec 5<&-