如何在添加变量参数? [英] How to add arguments on a variable?
问题描述
我有更新变量的值如下问题:
主脚本:
I have problems on updating the value of a variable as follows: THE MAIN SCRIPT:
#!/bin/bash
meniu()
{
echo "Select operation: "
echo -e "1 - add\n2 - bbb\n3 - ccc\n4 - ddd\n5 - eee\n"
read input
case $input in
1)
add $@
echo "The result is: " $sum
;;
2)
scadere $@
echo "fgh: " $diferenta
;;
3)
inmultire $@
echo "fgh: " $produs
;;
4)
impartire $@
echo "hfg: " $cat
;;
5)
modulo $@
echo "fgh: " $rest
;;
*)
echo Execution finished!
sleep 6
return
;;
esac
fi
}
meniu $@
函数SCRIPT:
#!/bin/bash
add()
{
n=$#
sum=$1
for (( i=2; i<=n; i++ ))
do
sum=$((sum + i))
done
}
我只想把由add函数返回的结果并显示。
这些脚本的工作,但只是对一些价值观。我注意到,当我使用的参数1或1比我我(从2开始)数量较少的增加变坏。
我认为,$((总和+ I))是这里的问题。 :(
任何sugesstions吗?
I just want to take the result returned by the add function and display it. The scripts are working but just for some values. I noticed that the adding goes bad when I use for arguments 1 1 or number smaller than my i (it starts from 2). I think that $((sum + i)) is the problem here. :( Any sugesstions please?
推荐答案
我觉得你用简单的测试,输入像1 2 3 4。您的附加功能是不使用的参数(除了第一个),用于添加,但该值循环变量的我:
I think you used simple test input like 1 2 3 4. Your add function is not using your parameters (except the first one) for adding, but the value of the loop variable i:
add()
{
n=$#
sum=$1
for (( i=2; i<=n; i++ ))
do
sum=$((sum + i))
done
}
add 1 2 3 4
echo "All seems well: sum=${sum}"
add 4 4 4
echo "I want 12, I got: sum=${sum}"
是你所试图做的是取消引用变量:
What you were trying to do is dereferencing the variables:
add()
{
n=$#
sum=$1
for (( i=2; i<=n; i++ ))
do
sum=$((sum + ${!i}))
done
}
add 1 2 3 4
echo "All seems well: sum=${sum}"
add 4 4 4
echo "I want 12, I got: sum=${sum}"
我会选择另一种解决办法,我会用移:
I would choose another solution, I would use shift:
add()
{
sum=0
while [ $# -gt 0 ]; do
sum=$((sum + $1))
shift
done
}
add 1 2 3 4
echo "All seems well: sum=${sum}"
add 4 4 4
echo "I want 12, I got: sum=${sum}"
这篇关于如何在添加变量参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!