If you are not familiar with Linux shell arrays, please see the previous article: Linux shell array establishment and usage skills. This article mainly focuses on the dynamic generation of array series. There should be many methods. I mainly take a problem of summation calculation as an example.
Title: please write a script with Linux shell to realize from 1 The sum of all even numbers in 1000.
Method 1:
Get the required results through the while loop:
start=1;
total=0;
while [ $start -le 1000 ];do
[[ $(($start%2)) == 0 ]]&&total=$(($total+$start));
start=$(($start+1));
done;
echo $total;
[[email protected] ~]$ start=1;total=0;while [ $start -le 1000 ];do [[ $(($start%2)) == 0 ]]&&total=$(($total+$start)); start=$(($start+1));done;echo $total;
250500
The above running results are: 249500, in the Linux shell, “;” As a command line separator. If you don’t understand the $(()) operation symbol, you can see the simple method for Linux shell to realize four operations (integer and floating point). For the [[]]] [] symbol, you can refer to another article for detailed explanation of Linux shell 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;
[[email protected] ~]$ start=0;total=0;for i in $(seq $start 2 1000); do total=$(($total+$i));done;echo $total;
250500
The above statement is obviously better than method 1 in terms of code, and the performance is also very good. The following comparison shows that:
Compare performance:
[[email protected] ~]$ time (start=0;total=0;for i in $(seq $start 2 1000); do total=$(($total+$i));done;echo $total;) 250500
real 0m0.016s
user 0m0.012s
sys 0m0.003s
[[email protected] ~]$ 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.073s
user 0m0.069s
sys 0m0.004s
Method 1 takes 6 times as long as method 2!
Seq usage:
seq [OPTION]... LAST
seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST
[ [email protected] ~]$SEQ 1000 'default is 1 for start and 1 for interval
[ [email protected] ~]$SEQ 2 1000 'interval is 1 by default
[ [email protected] ~]$SEQ 1 3 10 'the interval from 1 to 10 is 3. The result is: 1 4 7 10
Note: the default interval is "space". If you want to change to another one, you can take the parameter: - S
[[email protected] ~]$seq -s'#' 1 3 10
1#4#7#10
Application skills:
Generate continuous array series:
[[email protected] ~]$ a=($(seq 1 3 10))
[[email protected] ~]$ echo ${a[1]}
4
[[email protected] ~]$ echo ${a[@]}
1 4 7 10
Generate consecutive identical characters:
[[email protected] ~]$ seq -s '#' 30 | sed -e 's/[0-9]*//g'
#############################
The above example: after adding the interval character ‘#’, replace the number to generate the continuous same character ‘#’, which is still helpful in future writing.