1

This is the code that I have wrote in bash. The array arrKey is taking the user input and it's working well when I check. but I want to assign the elements in arrKey[] into new array K1[], then values are changing. For arrKey[0,1] and arrKey[1,0], I want to assign minus value in order to find the determinant of matrix later.

This is the Code:

  declare -A arrKey

  for ((i=0; i<2; i++)) do
      for((j=0; j<2;j++)) do
           read -p "Enter the key [$i, $j] =  :  " num
           arrKey[$i,$j]=$num
      done
  done

  declare -a K1
  K1[0,0]="$((arrKey[1,1] ))"
  K1[0,1]="$((0 - arrKey[0,1] ))"
  K1[1,0]="$((0 - arrKey[1,0] ))"
  K1[1,1]="$((arrKey[0,0] ))"

  echo ${arrKey[0,0]}
  echo ${arrKey[0,1]}
  echo ${arrKey[1,0]}
  echo ${arrKey[1,1]}
  echo
  echo ${K1[0,0]}
  echo ${K1[0,1]}
  echo ${K1[1,0]}
  echo ${K1[1,1]}

When I run array K1[] values not as expected.

  Enter the key [0, 0] = : 1
  Enter the key [0, 1] = : 2
  Enter the key [1, 0] = : 3
  Enter the key [1, 1] = : 4

  1
  2
  3
  4

  -3
  1
  -3
  1

Expected Output:

  Enter the key [0, 0] = : 1
  Enter the key [0, 1] = : 2
  Enter the key [1, 0] = : 3
  Enter the key [1, 1] = : 4

  1
  2
  3
  4

  4
  -2
  -3
  1
eddie
  • 1,252
  • 3
  • 15
  • 20
Mohamed Nuzhy
  • 105
  • 1
  • 8
  • 3
    You are declaring `K1` as a normal array not an associative array so the `0,0` assignments aren't doing what you expect they are. (Try using `declare -p arrKey K1` to print out the actual array values to see what I mean.) – Etan Reisner Aug 21 '16 at 20:23
  • `bash` doesn't have multi-dimensional arrays. See http://stackoverflow.com/questions/11233825/multi-dimensional-arrays-in-bash – Barmar Aug 21 '16 at 20:47
  • 1
    Excellent early Question, with code (gasp), sample input and debugging output. Keep posting and Good luck! – shellter Aug 21 '16 at 23:11
  • 1
    Based on your recent questions, you're trying to do things in bash -- arrays and math -- that bash really isn't good at. You can fake it, but you're likely to keep running into weird syntax issues, limitations, etc. I'd really recommend a almost any other language for things like this. – Gordon Davisson Aug 22 '16 at 04:14
  • 1
    thank you very much for your comments. Gordan Davisson, I have got an assignment to do hillcipher program in bash. that's why i'm struggling with bash script. – Mohamed Nuzhy Aug 22 '16 at 11:19

0 Answers0