1

I'm experiencing problems with a script converting numbers to bytes.

  • If the number is large enough to hit gigabytes or terabytes, the script runs as it should.
  • If the number converts to kilobytes, it runs the script, shows number in kilobytes and sends an error message at the same time.
  • If I'm in the megabyte interval, it only sends the error message:
line n ((: x > 1048576 : syntax error: invalid arithmetic operator (error token is " "). x represents the number I input.
tb=1099511627776 gb=1073741824 mb=1048576 kb=1024 read number if (( $number > $tb )); then echo "$(( number / tb )) terabytes" elif (( $number > $gb )) && (( $number < $tb )); then echo "$(( number > gb )) gigabytes" elif (( $number > $mb )) && (( $number < $gb )); then echo "$(( number > mb )) megabytes" elif (( $number > $kb )) && (( $number < $mb )); then echo "$(( number > mb )) kilobytes" fi 

Line n is the middle elif.

5
  • Use shellcheck.net and add ) in line 10.
    – Cyrus
    CommentedMar 11, 2015 at 22:14
  • Additionally change echo "$(( number > gb )) to echo "$(( number / gb )) == symbol > by /. More would like to test numfmt --to=iec command.
    – Costas
    CommentedMar 11, 2015 at 22:19
  • Finally for every elif, eliminate the && because it's already true.
    – ott--
    CommentedMar 11, 2015 at 22:31
  • Other bug fixes include replacing mb with kb in the kilobytes case, and thinking about what happens when the input is exactly equal to one of the constants (you can get rid of about half of the comparisons), or if it is lower than $kb.
    – dhag
    CommentedMar 12, 2015 at 4:27
  • t=$(((g=(m=(k=1024*(b=1))*k)*k)*k)), you can then do the check like for s in t g m k b; do [ "$((n>=$s))" -ne 0 ] && break; done || ! echo 0 bytes\! && echo "$((n/$s))${s#b}b"
    – mikeserv
    CommentedMar 12, 2015 at 8:53

2 Answers 2

2

There's an error in this line: echo "$(( number > gb ) gigabytes" there is a missing ).

The line should read: echo "$(( number > gb )) gigabytes"

1
  • Hey, thanks for pointing this out, but this is an error I only made while retyping the code here, and not in my script.
    – Thomas
    CommentedMar 12, 2015 at 8:22
1

I found the problem with the shellcheck checker, thanks @Cyrus. Apparently I had a non-breaking space (&nbsp) which I had to delete and make into a normal space at the middle elif between (( and $number. How does this happen?

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.