简体   繁体   English

UNIX:如何使我的脚本返回从命令行传递给它的数字的总和?

[英]UNIX: How do I make my script return the sum of the numbers passed to it from the command line?

Here is my current code: 这是我当前的代码:

for i do
    sum=$(expr $sum + $i)
done
echo =$sum

Now this works, but I want it to display all of the numbers. 现在可以使用,但是我希望它显示所有数字。 For example, If I enter ./sum 1 2 3, I want it to display 1+2+3=6. 例如,如果我输入./sum 1 2 3,我希望它显示1 + 2 + 3 = 6。 Right now it only displays the answer. 现在,它仅显示答案。 Also, is there a way I could execute the file without ./. 另外,有没有一种方法可以在没有./的情况下执行文件。 For instance, could I use sum 1 2 3 instead of ./sum 1 2 3. I've tried chmod 700 "myfile," but that didn't seem to work. 例如,我可以使用sum 1 2 3代替./sum 1 2 3吗?我试过chmod 700“ myfile”,但这似乎不起作用。

What about this? 那这个呢?

while (( $# > 1 )); do
    printf "$1 + "
    sum=$((sum + $1 ))
    shift
done
echo "$1 = $((sum + $1))"

It loops through the arguments you provide and adds them into the variable $sum . 它遍历您提供的参数,并将其添加到变量$sum For stylistic purposes I use printf and finally echo to have everything in the same line. 出于风格上的目的,我使用printf ,最后使用echo将所有内容放在同一行中。

The usage of shift is explained here: 这里解释了shift的用法:

The shift builtin command is used to "shift" the positional parameters by the given number n or by 1, if no number is given. 内置shift命令用于将位置参数“移位”给定数字n或1(如果未给出数字)。

Test 测试

$ sh script.sh 1 2 3
1 + 2 + 3 = 6
$ sh script.sh 1 2 3 4 5
1 + 2 + 3 + 4 + 5 = 15

You can use IFS and $* to join all the arguments with + : 您可以使用IFS$*将所有参数与+结合在一起:

(IFS="+"; printf '%s' "$*")

sum=0
for i; do
    sum=$((sum + i))
done
printf '=%d\n' "$sum"

To run without the ./ prefix, you need to put the program in a directory that appears in your PATH . 要在没有./前缀的情况下运行,您需要将程序放在PATH中显示的目录中。 Unless this is intended for people other than you, you should create a bin directory in your home directory, then add this to your .bash_profile : 除非这不是给您使用的,否则您应该在主目录中创建一个bin目录,然后将其添加到.bash_profile

PATH=~/bin/:$PATH

so that your bin directory is added to the list of places to look for commands. 以便将bin目录添加到查找命令的位置列表中。

Another answer: 另一个答案:

sum=0
for i in $@
do
    sum=$(($sum + $i))
done
echo $sum

Here a solution without loops: 这里是没有循环的解决方案:

numbers=$( printf -v str '%s+' $@; printf '%s' "${str%+}" )
sum=$(( $numbers ))
echo $numbers=$sum 

the first line joins the input arguments with +, the second line calculates the sum and the third line outputs the equation 第一行将输入参数与+相连,第二行计算总和,第三行输出等式

as to the second part of your question. 至于问题的第二部分。 Just put the script somewhere in your path (for example /usr/local/bin) 只需将脚本放在路径中的某个位置即可(例如/ usr / local / bin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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