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.

4
  • paste your script at shellcheck.net for validation, recomendation Commented Nov 5, 2021 at 4: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 Commented Nov 5, 2021 at 4: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? Commented Nov 5, 2021 at 4:37
  • Okay, Thanks a lot. Commented Nov 5, 2021 at 7:04

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.