简体   繁体   中英

Comparing argument in bash script function

I currently have the following function:

function abs()
{
  return ($1<0 ?-$1:$1);
}

When I try and run my script I am getting a syntax error:

bin/bash1.sh: line 5: syntax error near unexpected token `$1'
bin/bash1.sh: line 5: `  return ($1<0 ?-value:value);'

Could someone tell me how I should be writing this function?

Thank you.

The return statement in bash can't be used like that. It is only used to set the exit status of a function, and its argument (if present) must be an integer literal. If you want to communicate some other value back to the caller, you must use some other method.

You also need to use double-parentheses so that bash treats your expression as arithmetic; otherwise, it will treat <0 as an attempt to redirect stdin from a file named "0".

Try this instead:

function abs() { 
    echo $(($1<0 ?-$1:$1)); 
};
abs()
{
  echo $(($1<0 ?-$1:$1));
}

echo "abs -321 is $(abs -321)"

Guessing at syntax based on languages you already know is a viable strategy in languages like Java, C, C++, C# and Python, but unfortunately, it will not work in Bash. Try the Bash Guide for learning the language from scratch.

Command substitution is an option but use a global variable instead as it's expensive to forking.

function abs {
  (( __ = $1 < 0 ? -$1 : $1 ))
}

abs -4
echo "$__"

Output:

4

See Arithmetic Expansion and Shell Arithmetic (prev. Arithmetic Evaluation) .

  • (( __ = $1 < 0 ? -$1 : $1 )) is equivalent to __=$(( $1 < 0 ? -$1 : $1 )) .
  • () is unnecessary when declaring functions with function . abs() { } can be a form too and is compatible with original sh based shells but if you're just running your code with bash it doesn't matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM