How can I handle floating point arithmetic in my bash script?

0
10
Asked By CuriousCoder88 On

I'm trying to write a simple script that utilizes the `du` command, but I'm running into an issue with floating point math. I'm getting an error when I try to perform a calculation with a decimal, specifically: `arithmetic syntax error: invalid arithmetic operator (error token is ".6")`. However, when I run the same script directly in the terminal, it works fine. I'm using Zsh, but I've also tried running it with Bash. The problem line is:`echo " $((237 - $(cat $SC/tmp/du)))"`. Here's my complete script for context.

4 Answers

Answered By DataDude88 On

If you're only looking at file system usage, consider using `df /` or `df -BG /`. It directly gives you the numbers you need without any decimal issues.

Answered By SyntaxSavant99 On

Bash doesn't support floating point arithmetic directly. You should pipe the output to a tool like `bc` or `awk` instead. For example:
```bash
echo "237 - $(cat $SC/tmp/du)" | bc
``` Just make sure to format the command properly.

Answered By TechWhiz42 On

You should use `bc` for calculations involving floating points. Here's how it would look:
```bash
x=10
y=20
z=$(echo "$x + $y" | bc)

echo "z: $z"
``` That way, you can handle decimals without running into syntax errors.

Answered By ShellMaster15 On

If you're still facing issues after piping to `bc`, double-check your command. You might be inadvertently trying to perform the calculation in Bash itself. Instead, try this:
```bash
echo "237 - $(cat $SC/tmp/du)" | bc
``` This way, you're passing the whole string into `bc` for evaluation.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.