我实现了一个包含while for
循环的函数,其定义如下:
func()
{
...
for i in "$@"; do
enum="source"
sourceID=$i
ret_ID $FILE_NAME $sourceID $enum
ID=$req_ID
((ID+=ID))
done
echo $ID
}
函数ret_ID
解析包含一些变量的文件
param1=0x00000001
param2=0x00000400
param3=0x000008000
...
无论我传递多少个参数,echo $ID
都会返回与最后一个参数关联的ID,而不是所有参数的总和。例如,func param1 param3
返回32768
而非32769
。
答案 0 :(得分:1)
更新:根据OP的评论判断,glenn jackman建议切换让ret_ID()
设置全局变量为了将结果返回将其结果输出到stdout 并在命令替换中捕获结果($(...)
)解决了问题。
假设问题不是简单的逻辑错误,Glenn指出(((ID+=ID))
应该是((ID+=req_ID ))
:原始问题的确切原因不知道,但由于func()
和ret_ID()
都对全局变量进行操作,因此很容易看出一个函数如何干扰另一个函数,例如if ret_ID()
意外地还设置了变量$ID
。
这里'重写显示此更改的函数,并建议进行一些其他更改以使函数更加健壮,最明显的是使用本地变量强>:
func()
{
# Declare *local* variables.
local arg enum sourceID retID
# Declare the local result variable *as an integer*
# Also, better to use variable names that at least start with a *lowercase*
# letter to avoid conflicts with *environment* variables.
local -i id=0
# ...
for arg; do # loop over all args; the `in "$@"` part is optional
enum="source"
sourceID=$arg
# Call helper function and let it return its result via *stdout* captured
# through a command substitution rather than by setting a global variable.
# Note the use of double quotes to prevent problems with values with embedded spaces.
reqID=$(ret_ID "$FILE_NAME" "$sourceID" "$enum")
# Add the value returned to $id
# Note that since $id was declared as an integer,
# use of (( ... )) is optional.
id+=$reqID
done
echo "$id"
}