0

I am a beginner in bash script programming. I wrote a small script in Python to calculate the values of a list from an initial value up to the last value increasing with 0.5. The Python script is:

# A script for grid corner calculation. 
#The goal of the script is to  figure out the longitude values which increase with 0.5

# The first and the last longitude values according to CDO sinfo
L1 = -179.85
L2 = 179.979
# The list of the longitude values
n = []             

while (L1 < L2):
    L1 = L1 + 0.5
    n.append(L1)

print "The longitude values are:", n 
print "The number of longitude values:", len(n)

I would like to create a same script by bash shell. I tried the following:

!#/bin/bash
L1=-180
L2=180
field=()

while [ $L1 -lt $L2 ]
do
  scale=2
  L1=$L1+0.5 | bc
  field+=("$L1")

done

echo ${#field[@]}

but it does not work. Could someone inform me what I did wrong? I would appreciate if someone helped me.

3
  • doesn't work? not good enough. Maybe because floating point comparison isn't working in bash? Commented Jan 19, 2017 at 12:51
  • Your she-bang line is wrong, should have been #!/bin/bash Commented Jan 19, 2017 at 12:52
  • The array part is fine; it's the assignment to L1 that is wrong. Commented Jan 19, 2017 at 12:55

1 Answer 1

2

You aren't correctly assigning the value to L1. Also, -lt expects integers, so the comparison will fail after the first iteration.

while [ "$(echo "$L1 < $L2" | bc)" = 1 ]; do
do
  L1=$(echo "scale=2; $L1+0.5" | bc)
  field+=("$L1") 
done

If you have seq available, you can use that instead, e.g.,

field=( $(seq -f %.2f -180 0.5 179.5) )
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your quick answer. Both version works correctly.

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.