Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: loop through variables containing pattern in name

In my script I have an unknown number of variables containing angles which I want to convert to vectors. I made the variable-names such that the angles of each 'parameter' are of the form: {parameter}_angle_{lat/perp} Hence, each parameter has a 'lat' and 'perp' angle variable. So what I want to do is to find all variables containing '_angle_lat', do some calculations on the values of these variables and create a new variable which contains the 'parameter'-name in it. for example:

export M0_angle_lat=4
export M1_angle_lat=70
export M1_angle_perp=8
export M0_angle_perp=90

# Now I want to use these values to calculate vectors
for varname in *_angle_lat
do
    # at first iteration it will get for example "varname=M0_angle_lat" in which case
    # I want it to do:
    M0_X=$(( $M0_angle_lat * $M0_angle_perp ))
    # The second iteration in case would then give "varname=M1_angle_lat" in which case
    # I want it to do:
    M1_X=$(( $M1_angle_lat * $M1_angle_perp ))
done

I hope it's clear what my goal is here. Thanks for the help!

like image 794
Bjorn Avatar asked Sep 10 '14 12:09

Bjorn


1 Answers

What you can do is use env to get a list of all variables and then iterate through them:

while IFS='=' read -r name value ; do
  if [[ $name == *'_angle_lat'* ]]; then
    echo "$name" ${!name}
    prefix=${name%%_*} # delete longest match from back (everything after first _)
    angle_lat="${prefix}_angle_lat"
    angle_perp="${prefix}_angle_perp"
    result="${prefix}_X"
    declare "${result}=$(( ${!angle_lat} * ${!angle_perp} ))"       
  fi
done < <(env)
like image 194
RedX Avatar answered Sep 26 '22 00:09

RedX