This question already has an answer here:

The following (nested) function/s

function hpf_matrix {

  # Positional Parameters
  Matrix_Dimension="${1}"
  Center_Cell_Value="${2}"

  # Define the cell value(s)
  function hpf_cell_value {
    if (( "${Row}" == "${Col}" )) && (( "${Col}" == `echo "( ${Matrix_Dimension} + 1 ) / 2" | bc` ))
      then echo "${Center_Cell_Value} "
      else echo "-1 "
    fi
  }

  # Construct the Row for Cols 1 to "Matrix_Dimension"
  function hpf_row {
    for Col in `seq ${Matrix_Dimension}`
      do echo -n "$(hpf_cell_value)"
    done
  }

  # Construct the Matrix
  echo "MATRIX    ${Matrix_Dimension}"
  for Row in `seq ${Matrix_Dimension}`
    do echo "$(hpf_row)"
  done
  echo "DIVISOR   1"
  echo "TYPE      P"
}

work/s fine, both as a standalone code and inside a script. I.e. hpf_matrix 5 18 will return

MATRIX    5
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 18 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
DIVISOR   1
TYPE      P

and it will even work (with various values) as requested in:

Kernel_Size=5
Center_Cell_Default=18 ; Center_Level=Default
eval Center_Cell="Center_Cell_${Center_Level}"

HPF_MATRIX_ASCII=`hpf_matrix ${Kernel_Size} ${!Center_Cell}`
echo "${HPF_MATRIX_ASCII}"

However, integrating without any changes the above pieces of code (the hpf_matrix function and feeding the "${HPF_MATRIX_ASCII}") inside a larger bash script, errors-out with the following message:

((: 1
2
3
4
5 == 1
2
3
4
5 : syntax error in expression (error token is "2
3
4
5 == 1
2
3
4
5 ")

Minor Update

If I understand correctly, for whatsoever is the reason behind, the line

for Row in seq ${Matrix_Dimension}

as well as the line

for Col in seq ${Matrix_Dimension}

are printed as "1 2 3 4 5" instead of "1" "2" "3" "4" "5".

What is wrong in this case? I would like to keep a nested structure for the function unless it is clearly wrong.

marked as duplicate by Michael Mrozek Nov 5 '13 at 20:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 1 down vote accepted

In the large script, in which the above function was integrated to work as part of it, and prior of defining the hpf_matrix function, the IFS has been changed to IFS=, without taking care to reset it back before using the unquoted command substitution in the function!

An explanation on Using unquoted command substitution ($(...)) without setting $IFS here: https://unix.stackexchange.com/a/88259/13011.

A solution to this also here: https://unix.stackexchange.com/a/92188/13011.

Not the answer you're looking for? Browse other questions tagged or ask your own question.