开发者

Bash Script to add first 10 numbers i.e 1 to 10 using control statement

开发者 https://www.devze.com 2023-03-07 09:58 出处:网络
I want to know how can we add the first 10 numbers using bash script. The addition should be done using control statement. D开发者_开发问答o I need to use Array ? if someone can show me an example the

I want to know how can we add the first 10 numbers using bash script. The addition should be done using control statement. D开发者_开发问答o I need to use Array ? if someone can show me an example then I would very thankful.

Thanks.


Try this script in bash:

for i in {1..10}; do s=$((s+i)); done; echo $s

OUTPUT

55


seq -s + 1 10 | bc -ql

This is perhaps a contrived answer, but it does the job..

  • -s uses the given argument to separate the output. In this way we can build the output string for bc
  • seq takes up to 3 arguments, last, first and last, or first increment and last.

bc is a calulator:

  • -q means quiet
  • -l means include mathlib -- probably not necessary but won't hurt.

Check out man seq/bc for the juicy details..

0

精彩评论

暂无评论...
验证码 换一张
取 消