Another portable POSIX
compliant way to do in bash
, which can be defined as a function in .bashrc
for all the arithmetic operators of convenience.
addNumbers () {
local IFS='+'
printf "%s\n" "$(( $* ))"
}
and just call it in command-line as,
addNumbers 1 2 3 4 5 100
115
The idea is to use the Input-Field-Separator(IFS), a special variable in bash
used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +
.
Remember the IFS
is changed locally and does NOT take effect on the default IFS
behaviour outside the function scope. An excerpt from the man bash
page,
The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.
The "$(( $* ))"
represents the list of arguments passed to be split by +
and later the sum value is output using the printf
function. The function can be extended to add scope for other arithmetic operations also.