The absolute value of the number

I want to take an absolute number with 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 the if statement, no matter what I change, it always goes in the if, I tried to put [[ ]] around the instruction, but nothing.

Here is the error:

 ./p6.sh: line 13: [: : integer expression expected 
+14
source share
3 answers
 $ s2=5 s1=4 $ echo $s2 $s1 5 4 $ res= expr $s2 - $s1 1 $ echo $res 

What actually happens on the fourth line is that res is not set and exported to the expr command. Thus, when you run [ "$res" -lt 0 ] res expands to zero, and you see an error.

You can simply use an arithmetic expression :

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

The arithmetic context ensures that the result will be integer, so even if all your terms are undefined, 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 

Interestingly, the right-hand side of the job is processed in an arithmetic context, so you don't need $ for extensions.

+5
source

You can just take ${var#-} .

${var#Pattern} Remove from $var the shortest part of $Pattern corresponding to the outer end of $var . tdlp


Example:

 s2=5; s1=4 s3=$((s1-s2)) echo $s3 -1 echo ${s3#-} 1 
+15
source

I know this thread is old at the moment, but I wanted to share a function that I wrote that could help with this:

 abs() { [[ $[ $@ ] -lt 0 ]] && echo "$[ ( $@ ) * -1 ]" || echo "$[ $@ ]" } 

This will take any mathematical / numeric expression as an argument and return an absolute value. For example: abs -4 => 4 or abs 5-8 => 3

0
source

Source: https://habr.com/ru/post/984164/


All Articles