Absolute value of a number

后端 未结 4 1949
梦毁少年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: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.

提交回复
热议问题