Below code is what i do currently. However it doesn't work out for all cases. As some times the last digit extracted is giving me error. It cant be used for arithmetic computation.
Any better methods out there? If possible, can you please explain to me why the last digit extracted out cant be used for arithmetic computation? Thanks !
First off: you shouldn't use backticks any more, they are deprecated in every modern shell. But that just as an aside, it shouldn't cause your problem.
The last "number" might be no number at all, as there might be trailing blanks or something such in it. To the shell "everything is a string" and even numbers are strings containing only digits. Your variable expansion statements manipulate strings (by cutting off certain parts), it is just your implicit knowledge of the values involved to justify using these as numbers at all.
I suggest to make sure the variables are indeed what you expect them to be (numbers) by adding some debugging code to your script and output them quoted strictly and surrounded by delimiters to make leading/trailing characters show:
echo "var_in_question is \"${var_in_question}\"" > some_log
Does you input comes from a file that is dynamically generated (so that its content changes) ?
or is your input taken from a configuration file whose content does not change ? (configured just once)
Maybe you'd better to just setup an environment file in which you set the wanted variables so that you could load them directly by executing it.
You can create an array. The basic way to create it is:
set -A ARRAYNAME $(some process with linewise output)
Run the following to get a feeling for this. I suggest you read the man page of "ksh" carefully about arrays to see what can be done using these:
set -A filelist $(ls) # put every line of "ls" output into an array element
typeset index=0
while [ $index -le ${#filelist[*]} ] ; do # ${#var[*]} means: number of elements in array "var"
echo "Element number $index contains: ${filelist[$index]}"
(( index += 1 ))
done
The other usual shell method is to work in a loop on one item after the other, being fed into the loop with a pipeline. The above using such a loop:
typeset -i index=0
ls | while read filename ; do # set "filename" to one filename after the other
echo "File number $index is: $filename"
(( index += 1 ))
done