Home > Back-end >  How to output decimal variables in bash
How to output decimal variables in bash

Time:07-12

I have a simple code where I'm just trying to print out a bunch of values, but one of the values is a decimal. I've seen a bunch of answers involving using the | bc function, and I've incorporated that here, but I still can't get the output correct. The code works fine if I use integer values. I would use a c-shell, however my end goal is to run a fortran code with these values that I compile with a specific .cshrc file, and I'd rather not mess with that .cshrc file any more than I have to.

#!/usr/bin/bash

theta1="15"
bmag1="1"
az1="-0.5" | bc
dtheta="15"
dbmag="1"
daz="0.5" | bc
for i in {1..3}
do
  theta=$((theta1   $((i - 1)) * dtheta))
  for j in {1..3}
  do
    bmag=$((bmag1   $((j - 1)) * dbmag))
    for k in {1..3}
    do
      az=$((az1   $((k - 1)) * daz)) | bc
      echo "$theta $bmag $az"
    done
  done
done

CodePudding user response:

You are confused about the role of bc. It's not used to turn a string that looks like a floating-point value into an actual floating point value. If it did, you'd still have to write az1=$(echo "-0.5" | bc). But bash has no concept of numbers as a data type. You can write az1="-0.5" just as easily as you can write az1="-1".

The problem is that bash can only perform integer operations on integer-like string values. It's in computing things like az where you need to use bc:

az=$( echo "$az1   ($k-1) * $daz" | bc )

The input to bc is a single string which bc itself will parse and evaluate before writing back the result as a string to standard output, which the shell can capture for later use.

  •  Tags:  
  • bash
  • Related