Linux shell dynamically generated array series seq tips

  
 

Title: Please use the linux shell to write a script that implements the sum of all even numbers from 1..1000.


Method one:

Get the desired result through the while loop:

start=1;

total=0;< Br>

while [ $start -le 1000 ];do

[[ $(($start%2)) == 0 ]]&&total=$(($total+$start ));

start=$(($start+1));

done;

echo $total;


[chengmo@centos5 ~]$ start=1;total=0;while [ $start -le 1000 ];do [[ $(($start%2)) == 0 ]]&&total=$( ($total+$start)); start=$(($start+1));done;echo $total;250500

The above result is: 249500, in the linux shell, ”;” As a command line separator. If you don't understand the $(()) operator, you can check: The linux shell implements four arithmetic (integer and floating point) simple methods. If you are using the [[]] [] symbol, you can refer to another article linux shell. Detailed explanation of logical operators and logical expressions.


Method 2:

Get the result through the 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));done; Echo $total; 250500


The above statement is significantly better than the first method in terms of code, and the performance is also very good. The following comparison can be found:



Comparative performance:

[chengmo@centos5 ~]$ time (start=0;total=0; For i in $(seq $start 2 1000); do total=$(($total+$i));done;echo $total;) 250500

real 0m0.016suser 0m0.012ssys 0m0.003s[ ,null,null,3],Chengmo@centos5 ~]$ time (start=1;total=0;while [ $start -le 1000 ];do [[ $(($start%2)) == 0 ]]&&total=$( ($total+$start)); start=$(($start+1));done;echo $total;) 250500

real 0m0.073suser 0m0.069ssys 0m0.004s

Method one time is six times the method two!



seq Use:

seq [OPTION]... LASTseq [OPTION]... FIRST LASTseq [OPTION]... FIRST INCREMENT LAST

[chengmo@centos5 ~]$ seq 1000 ‘ The default is 1 and the default is 1

[chengmo@centos5 ~]$seq 2 1000 ‘ 1

[chengmo@centos5 ~]$seq 1 3 10 'From 1 to 10 Interval is 3 Results are: 1 4 7 10

Description: The default interval is "Space" If you want to change to other, you can take the parameter: -s

[chengmo@centos5 ~]$seq -s'#' 1 3 10

1#4#7#10


application skills:


  • generate a continuous array of series:



    [chengmo @centos5 ~]$ a=($(seq 1 3 10)) [chengmo@centos5 ~]$ echo ${a[1]}4[chengmo@centos5 ~]$ echo ${a[@]}1 4 7 10




  • generation consecutive identical characters:



    [chengmo @ centos5 ~] $ seq -s '#' 30

  • Copyright © Windows knowledge All Rights Reserved