2

On Ubuntu 14.04.1 64-bit LTS I am writing a shell script and if I define the start of the sequence used in the for loop with a variable instead of a constant I get really weird behavior and there are lots of errors from the bc calculator. You can run the following code snippet to reproduce the errors:

#!/bin/bash
S=0.030
F=0.150
N=30
DIFF=`echo $F - $S | bc -l`
dw=`echo $DIFF / $N | bc -l`
is=`echo $S / $dw | bc -l`
if=`echo $F / $dw | bc -l`
for i in `seq $is $if` 
    do
        w=`echo "scale=3; $i * $dw" | bc -l`
done

If I change the start of the sequence to a constant it works perfectly, but when it is a variable there are problems the output is as follows:

(standard_in) 1: syntax error
...
...
(standard_in) 1: syntax error

What may be the reason behind this behaviour? I would like to receive your suggestions and comments.

12
  • 1
    I ran your program with bash 4.3.30(1)-release , i didn't prevent with any error. – PersianGulf Dec 24 '14 at 1:14
  • Hmm the following is my Bash version but the problem persists it is really weird. GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) – Vesnog Dec 24 '14 at 1:16
  • Please wait until i test with dash. – PersianGulf Dec 24 '14 at 1:17
  • 2
    I don't see the issue and I am using Bash 4.3.11(1)-release as well. The seq is working properly as well as the bc. @Vesnog, have you narrowed down which statement is causing the syntax error (add set -x to the beginning of the script)? – Arcege Dec 24 '14 at 1:51
  • 1
    So use perl, python or ruby ?! – Gilles Quenot Dec 24 '14 at 4:10
2

The problem turned out to be that the decimal point separator in my Ubuntu installation was set to , (comma) instead of . (dot). I changed it with the following command:

sudo update-locale LC_NUMERIC="en_GB.UTF-8"

And the problem was resolved.

4
  • Put export LC_NUMERIC=C at the start of your script, that way it'll be robust against the system configuration. – Gilles 'SO- stop being evil' Dec 24 '14 at 20:09
  • @Gilles Okay so what will C do in this case? – Vesnog Dec 24 '14 at 22:21
  • C means “use default settings” (so . as the decimal separator, etc.). Setting it explicitly in your script overrides whatever the environment might have set. – Gilles 'SO- stop being evil' Dec 24 '14 at 22:24
  • By redefining the environmental variable, right? – Vesnog Dec 24 '14 at 22:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.