Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in Bash script arithmetic syntax

Tags:

bash

Script:

#!/bin/bash
vpct=5.3 
echo $((vpct*15))    

Error:

./abc.sh: line 5: 5.3: syntax error: invalid arithmetic operator (error token is ".3")

I know I don't need a script to multiply 5.3 * 15, but this small script to single out the error. Please advise.

like image 531
Humble Debugger Avatar asked Feb 18 '11 11:02

Humble Debugger


People also ask

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What is if [- Z in Bash?

In both cases, the -z flag is a parameter to the bash's "test" built-in (a built-in is a command that is built-into the shell, it is not an external command). The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something.

What does != Mean in Bash?

The origin of != is the C family of programming languages, in which the exclamation point generally means "not". In bash, a ! at the start of a command will invert the exit status of the command, turning nonzero values to zero and zeroes to one.


1 Answers

According to http://www.softpanorama.org/Scripting/Shellorama/arithmetic_expressions.shtml:

Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings.

You should use bc to perform such calculations, just as in dogbane's solution, except that you should escape the expression using quotes so the * character doesn't cause unwanted shell expansion.

echo "$vpct*15" | bc
like image 60
SirDarius Avatar answered Sep 29 '22 00:09

SirDarius