2

I am trying to update a variable within a for loop, sequentially adding to the variable, and then printing it to a series of file names.

Actually, I want to sequentially update a series of file, from a tmp file distTmp.RST to sequentially dist1.RST, dist2.RST, etc.. The original distTmp.RST contains a line called "WWW". I want to replace the string with values called 21.5 in dist1.RST, 22.5 in dist2.RST, 23.5 in dist3.RST, etc...

My code is as follows:

#!/bin/bash

wm=1
wM=70
wS=1

F=20.5

for W in {${wm}..${wM}..${wS}}; do

    F=$(${F} + 1 | bc)
    echo ${F}
    sed "s/WWW/"${F}"/g" distTmp.RST > dist${W}.RST 
done
echo ${F}

========

But I am getting error message as follows:

change.sh: line 13: 20.5 + 1 | bc: syntax error: invalid arithmetic operator (error token is ".5 + 1 | bc")

Kindly suggest me a solution to the same.

Jetchisel
  • 7,493
  • 2
  • 19
  • 18
Prathit
  • 27
  • 5
  • paste your script at https://shellcheck.net for validation, recomendation – Jetchisel Nov 05 '21 at 04:20
  • 1
    shellcheck.net will detect lots of issues with your script, but one issue that might get 'missed' is the potentially problematic bc command; try changing `F=$(${F} + 1 | bc)` to `F=$(echo "${F} + 1" | bc)` and see if you still get the syntax error – jared_mamrot Nov 05 '21 at 04:35
  • 1
    The problem isn't the addition, it's the range expression you're trying to iterate over -- bash doesn't allow you to use variables in a brace expression. See: [How do I iterate over a range of numbers defined by variables in Bash?](https://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-defined-by-variables-in-bash) – Gordon Davisson Nov 05 '21 at 04:37
  • Okay, Thanks a lot. – Prathit Nov 05 '21 at 07:04

2 Answers2

4

Kindly suggest me a solution to the same.


This might do what you wanted. Using a c-style for loop.

#!/usr/bin/env bash

wm=1
wM=70
wS=1

F=20.5

for ((w=wm;w<=wM;w+=wS)); do
  f=$(bc <<< "$F + $w")
  echo "$f"
  sed "s/WWW/$f/g" distTmp.RST > "dist${w}.RST"
done

  • The error from your script might be because the order of expansion. brace expansion expansion happens before Variable does.

  • See Shell Expansion

Jetchisel
  • 7,493
  • 2
  • 19
  • 18
1

Use

F=$(echo ${F} + 1 | bc)

instead of F=$((${F} + 1 | bc)). The doubled-up parentheses are what caused your error. Double parentheses weren't in the original code, but I get a different error saying 20.5: command not found with the original code, so I tried doubling the parentheses and get the error in the question. Apparently, floating point numbers aren't supported by $(()) arithmetic evaluation expressions in Bash.

Nathan Mills
  • 2,243
  • 2
  • 9
  • 15
  • I don't see a double `((` from the OP's post, but on the other hand, you're right about not having an `echo` inside the command substitution. Which obviously I have not pointed out from my answer. – Jetchisel Nov 05 '21 at 04:59