Absolute value of a number

后端 未结 4 1902
梦毁少年i
梦毁少年i 2021-01-17 08:41

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 f         


        
相关标签:
4条回答
  • 2021-01-17 09:13

    I know this thread is WAY old at this point, but I wanted to share a function 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 the absolute value. For instance: abs -4 => 4 or abs 5-8 => 3

    0 讨论(0)
  • 2021-01-17 09:16

    A workaround: try to eliminate the minus sign.

    1. with sed
    x=-12
    x=$( sed "s/-//" <<< $x )
    echo $x
    
    12
    
    1. Checking the first character with parameter expansion
    x=-12
    [[ ${x:0:1} = '-' ]] && x=${x:1} || :
    echo $x
    
    12
    

    This syntax is a ternary opeartor. The colon ':' is the do-nothing instruction.

    1. or substitute the '-' sign with nothing (again parameter expansion)
    x=-12
    echo ${x/-/}
    
    12
    

    Personally, scripting bash appears easier to me when I think string-first.

    0 讨论(0)
  • 2021-01-17 09:20

    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
    
    0 讨论(0)
  • 2021-01-17 09:27
    $ 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.

    0 讨论(0)
提交回复
热议问题