In below function with 9 arguments:
SUM() {
echo "The sum is $(($1+$2+$3+$4+$5+$6+$7+$8+$9))"
}
I want to make the second arguments to the next(3..9) become a optional arguments.
When I call the function with 2 arguments I get error:
SUM 3 8
bash: 3+8+++++++: syntax error: operand expected (error token is "+")
Note BOLD: first argument and second argument are force arguments and not optional for function. I only want second arguments to the next is optional and when I call the function less than 2 args the function must return no result.
If you won't pass arguments with spaces:
Effect:
Explanation:
<<<"some string"
feeds in only"some string"
as the input. Think of it as shorthand forecho "some string" |
. It is called a Here String."$@"
expands into all the positional parameters, separated by spaces. It is equivalent to"$1 $2 ..."
.tr ' ' '+' <<<"$@"
outputs"$1+$2+$3..."
, which is evaluated by the outer$(( ))
.[[ -n $2 ]]
tests if the second parameter is non-empty. You could replace[[ -n $2 ]] &&
with[[ -z $2 ]] ||
.Another way:
Explanation:
$*
is just like$@
, except that the parameters are not separated by spaces, but by the first character of the Internal Field Separator (IFS
). WithIFS=+
, it expands to "$1+$2+...". See What is the difference between $* and $@?IFS
in a subshell (note the surrounding parentheses) so that the main shell isn't affected.IFS
is, by default:\t\n
(space, tab, newline). This is an alternative to usinglocal
variables.Now to answer your question:
You can use a default value for any variable or parameter. Either:
Or:
Have a look at the
shift
operator. It will shift arguments 2 and onward to positions 1 and onward, discarding argument 1.You could use a recursive definition which terminates when
sum
is invoked without arguments. We make use of the fact thattest
without arguments evaluates tofalse
.Try this:
This will output 12 and 30.
$@
refers to parameter,$#
returns the number of parameter, in this case 3 or 11.Tested on linux redhat 4
You could just use a little loop:
Personally though, I'd just use
perl
orawk
instead:or
Use 0 as default values for $1 to $9:
From
man bash
:Examples:
The sum is 0
The sum is 3
The sum is 9
Same output with awk:
It's also my own solution I tried it and found:
But @muru's answer is good.