Thursday, 20 February 2020

Work with 2D Array and Floating-point Numbers in Bash

Bash supports only 1D array, however, there's a work-around, for example:

List=("value00 value01" "value10 value11" "value20 value21");

#Example I,J
I=1;
J=1;
Row=(${List[I]}); #Wrap in parentheses
Cell=${Row[J]};

Bash supports only integers, the work-around to do floating-point maths is creating new functions based on something like Perl:

function + {
  perl -e "print($1 + $2)";
}

function - {
  perl -e "print($1 - $2)";
}

function x { #Can't use *, Bash expands * to files
  perl -e "print($1 "'*'" $2)";
}

function / {
  perl -e "print($1 / $2)";
}

function p { #A to power B
  perl -e "print(($1) ** $2)"; #Parentheses for negative values
}

function random {
  printf $(/ $RANDOM 32767);
}

#Examples of using those functions:
echo $(+ $(random) $(random));
echo $(- $(random) $(random));
echo $(x $(random) $(random));
echo $(/ $(random) $(random));
echo $(p $(random) $(random));

No comments:

Post a Comment