2

I have read all previous post about float numbers divisions in bash but I can't solve my problem...

I have this bash script:

lengthseq=$(sed -e 's/^\(>\).*//' sequence.fasta | sed '1d' | tr -d "\n" | awk '{ print length }')
lengthcodons=$("$lengthseq/3" | bc -l)

echo $lengthseq
echo $lengthcodons

Lengthseq it's ok. echo $lengthseq prints 2275859.

If I run it in konsole:

echo "2275859/3" | bc -l
758619.66666666666666666666

It's okay too.

So I don't understant why if I try it in my script, $lengthcodons generates and error.

userbio
  • 115
  • 3
  • 14
  • Could I ask you want the command `lengthseq=$(sed -e 's/^\(>\).*//' sequence.fasta | sed '1d' | tr -d "\n" | awk '{ print length }')` does? (in fact, I'd like to know if it's really doing what you're expecting). – gniourf_gniourf Nov 10 '13 at 16:31
  • Possible duplicate of [How do I use floating-point division in bash?](https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash) – Andrea Corbellini Apr 29 '18 at 02:05

3 Answers3

3

Correct syntax of using bc -l is:

lengthcodons=$(bc -l <<< "$lengthseq/3")
echo "$lengthcodons"
758619.66666666666666666666

Or with scale=2

lengthcodons=$(bc -l <<< "scale=2; $lengthseq/3")
echo "$lengthcodons"
758619.66
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

You're missing echo in following line

lengthcodons=$(echo "$lengthseq/3" | bc -l)
jkshah
  • 11,387
  • 6
  • 35
  • 45
1

Here:

lengthcodons=$("$lengthseq/3" | bc -l)

You're executing the line "2275859/3" | bc -l and put the result in lengthcodons, your forgot the echo.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75