Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute value of a number

Tags:

I want to take the absolute of a number by the following code in bash:

#!/bin/bash echo "Enter the first file name: " read first  echo "Enter the second file name: " read second  s1=$(stat --format=%s "$first") s2=$(stat -c '%s' "$second")  res= expr $s2 - $s1  if [ "$res" -lt 0 ] then         res=$res \* -1 fi  echo $res 

Now the problem I am facing is in the if statement, no matter what I changes it always goes in the if, I tried to put [[ ]] around the statement but nothing.

Here is the error:

./p6.sh: line 13: [: : integer expression expected 
like image 629
Ali Sajid Avatar asked Mar 24 '15 01:03

Ali Sajid


People also ask

What is the absolute value of |- 5?

The absolute value of -5: |−5| is the absolute value of a negative number. To find the answer to this, you simply remove the negative sign, so the answer is 5 .

What is the absolute value of |- 12?

The absolute value of -12 is 12. Since the distance between -12 and 0 in a number line is 12.

What is the absolute value of 3?

For example, the absolute value of 3 is 3, and the absolute value of −3 is also 3. The absolute value of a number may be thought of as its distance from zero.

What is the absolute value of 10?

Number 10 has no sign i.e. it is positive and hence, we can say that |10|=10 . Graphically, absolute value of a number can be described as distance of its location on real number line from origin i.e. point described as 0 , irrespective of its direction, whether towards positive or negative side of origin.


2 Answers

You might just take ${var#-}.

${var#Pattern} Remove from $var the shortest part of $Pattern that matches the front end of $var. tdlp


Example:

s2=5; s1=4 s3=$((s1-s2))  echo $s3 -1  echo ${s3#-} 1 
like image 173
Suuuehgi Avatar answered Oct 08 '22 13:10

Suuuehgi


$ s2=5 s1=4 $ echo $s2 $s1 5 4 $ res= expr $s2 - $s1 1 $ echo $res 

What's actually happening on the fourth line is that res is being set to nothing and exported for the expr command. Thus, when you run [ "$res" -lt 0 ] res is expanding to nothing and you see the error.

You could just use an arithmetic expression:

$ (( res=s2-s1 )) $ echo $res 1 

Arithmetic context guarantees the result will be an integer, so even if all your terms are undefined to begin with, you will get an integer result (namely zero).

$ (( res = whoknows - whocares )); echo $res 0 

Alternatively, you can tell the shell that res is an integer by declaring it as such:

$ declare -i res $ res=s2-s1 

The interesting thing here is that the right hand side of an assignment is treated in arithmetic context, so you don't need the $ for the expansions.

like image 31
kojiro Avatar answered Oct 08 '22 14:10

kojiro