0

I'm using a bash script to run a program with several variables using a series of nested for loops, one of which needs to include decimals. As part of the process of switching between various sub-directories, I also need to be able to multiply that value by a constant, and that's the part that's giving me trouble. So for example:

#!/bin/bash

for a in 600 700 800
do
    for c in 0 0.1 0.15
    do
        d=echo "$((100 * $c))" | bc -l

        cd "$a"X/Y"$d"Z
        pwd
        cd ../../
    done
done

Where X, Y, and Z are just text designators in the subdirectories. The issue I'm having is with getting an actual value for $d. I've tried all the solutions from this question: Multiplication on command line terminal and haven't gotten any of them to work. Is there another way to do this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    The smallest change that would fix your code would be `d=$(echo "100 * $c" | bc -l)` -- note the surrounding `$(...)`. What you have right now is assigning the value `echo` to the variable `d` while running the output of multiplying `c` by `100` *as a command*, and piping the output of that command (which is expected to fail and have no output at all, because numbers aren't generally programs you can run) to the input to `bc`. – Charles Duffy May 01 '20 at 16:35
  • 1
    BTW, consider `(cd "${a}X/Y${d}Z" && pwd)` so you scope the `cd` and thus don't need to back it out. The current `cd ../..` code will still go back two directories even if the earlier `cd` code didn't successfully go *down* two directories, so you can end up somewhere that wasn't your starting point. – Charles Duffy May 01 '20 at 16:38
  • @CharlesDuffy Thanks that makes sense! – Sean Masengale May 01 '20 at 18:14

0 Answers0