简体   繁体   中英

Easy increment and print values at the same time

I need help incrementing array values inside loops. The problem is variables are all the same and the second element of "Numbers" array is not incremented.

#!/bin/bash

Duration=60

declare -a Numbers=("5" "10")

for (( d=1 ; d<=$Duration ; d++ ))
do

  for (( i=0 ; i<${#Numbers[@]} ; i++ ))
  do

        if [ "$MYVALA" == "" ]; then
                MYVALA=${Numbers[i]}
        else
                MYVALA=$(($MYVALA+1))
        fi ;

        echo ""
        echo "number: ${Numbers[i]}"
        echo "-------------"
        echo "new value = $MYVALA"
  done ;
  sleep 1 ;
done ;

this is the result of code above:

number: 5
-------------
new value = 5

number: 10
-------------
new value = 6

number: 5
-------------
new value = 7

number: 10
-------------
new value = 8

What I would like to get is:

number: 5
-------------
new value = 6

number: 10
-------------
new value = 11

number: 5
-------------
new value = 7

number: 10
-------------
new value = 12
...

number 5 and number 10 are printed at the same time and once per second.

Thanks for your help.

This produces the output you wanted. The new value is simply the number plus duration.

#!/bin/bash

Duration=60
Numbers=(5 10)

for (( d=1 ; d<=Duration ; d++ )) ; do
  for (( i=0 ; i<${#Numbers[@]} ; i++ )) ; do
      let MYVALA=Numbers[i]+d
      echo
      echo "number: ${Numbers[i]}"
      echo '-------------'
      echo "new value = $MYVALA"
  done
  sleep 1
done

To increment an array value, use (( myarray[i]++ )) . To make your script print out the values you describe, you can keep a separate array of counters for each number.

#!/bin/bash

Duration=60

declare -a Numbers=("5" "10")
Counters=( "${Numbers[@]}" )

for (( d=1 ; d<=$Duration ; d++ ))
do

  for (( i=0 ; i<${#Numbers[@]} ; i++ ))
  do
        (( Counters[i]++ ))
        echo ""
        echo "number: ${Numbers[i]}"
        echo "-------------"
        echo "new value = ${Counters[i]}"
  done ;
  sleep 1 ;
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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