If you're not familiar with the Linux shell array, see an article: The Linux shell array build and use techniques, this article is mainly about dynamically generating array series. There should be a lot of methods here, I mainly take a sum calculation of the problem as an example to analyze.
Topic: Please write a script with Linux shell, implement from 1. 1000 and values of all even numbers.
Method One:
The desired result is obtained through a while loop:
Start=1;
total=0;
While [$start-le 1000];d o
[[$ ($start%2)] = = 0]]&&total=$ (($total + $start));
start=$ (($start + 1));
Done;
echo $total;
[Chengmo@centos5 ~]$ start=1;total=0;while [$start-le 1000];d o [[$ ($start%2)] = = 0]]&&total=$ ($total +$ Start)); start=$ (($start + 1));d One;echo $total;
250500
The above results are: 249500, in the Linux shell, ";" As a command line separator. If you are not very understanding of the $ (()) operation symbol, you can view: Linux shell Implementation arithmetic (integer and floating-point) simple method, if for: [[]] [] symbol, you can refer to another article Linux shell logical operators, logical expression of the detailed explanation.
Method Two:
Get results with a For loop:
start=0;
total=0;
For I in $ (Seq $start 2 1000); Do
total=$ (($total + $i));
Done;
echo $total;
[Chengmo@centos5 ~]$ start=0;total=0;for i in $ (Seq $start 2 1000); Do total=$ (($total + $i));d One;echo $total;
250500
The above statement is obviously better than method one in terms of code, and performance is also good. Here's a comparison to find out:
Compare performance:
[Chengmo@centos5 ~]$ Time (start=0;total=0;for i $ (seq $start 2 1000), do total=$ ($total + $i));d One;echo $total;) 250500
Real 0m0.016s
user 0m0.012s
sys 0m0.003s
[chengmo@centos5 ~]$ Time (Start=1;total=0;while [$start-le 1000];d o [[$ ($start%2)] = = 0]]&&total=$ (($total + $start)); start=$ (($start + 1));d one;echo $total;)
250500
real 0m0.073s
user 0m0.069s
sys 0m0.004s
Method one time is 6 times times of method two!
seq Use:
seq [OPTION] ... Last
seq [OPTION] ... The last
seq [OPTION] ... First INCREMENT
[chengmo@centos5 ~]$ seq 1000 ' starts by default is 1, interval default is also 1
[chengmo@centos5 ~] $seq 2 1000 ' interval default is 1< C6/>[CHENGMO@CENTOS5 ~] $seq 1 3 ' starting from 1, to 10 intervals of 3 The result is: 1 4 7
Note: The default interval is "space" if you want to change to another can with parameters:-S
[ CHENGMO@CENTOS5 ~] $seq-S ' # ' 1 3
1#4#7#10
Application tips:
To generate a continuous array series:
[Chengmo@centos5 ~]$ a= ($ (SEQ 1 3))
[Chengmo@centos5 ~]$ echo ${a[1]}
4
[chengmo@centos5 ~]$ Echo ${a[@ ]}
1 4 7 10
Generate consecutive same characters:
[Chengmo@centos5 ~]$ seq-s ' # ' 30 | Sed-e ' s/[0-9]*//g '
#############################
The above example: by adding the interval character ' # ', replace the number, generate a continuous same character ' # ', this in the future writing will still have a lot of help.