简体   繁体   中英

list accumulation in bash scripting

How to do list accumulation in bash, in python I can do this way, but in bash I can not get it to work anyhow.

from itertools import accumulate

def list_accumulation(lst):
  output = list(accumulate(map(int,lst)))
return output

list_accumulation([1,2,3]) >>> [1, 3, 6]

As the function of bash cannot return list , let me express it with a string of space separated values:

#!/bin/bash

list_accumulation() {
    local lst i
    IFS=" " read -r -a lst <<< "$1"
    for (( i = 1; i < ${#lst[@]}; i++ )); do
        (( lst[i] += ${lst[i-1]} ))
    done
    echo "${lst[*]}"
}

list_accumulation "1 2 3"

Output:

1 3 6

As tshiono said, bash function cannot return list. You can use name-ref to achieve similar effects:

#!/usr/bin/env bash

list_accumulation(){
    declare -n list_accumulation_internal_list=$1; local i
    for (( i = 1; i < ${#list_accumulation_internal_list[@]}; i++ )); do
        (( list_accumulation_internal_list[i] += ${list_accumulation_internal_list[i-1]} ))
    done
}

list=(1 2 3)
list_accumulation list
echo "${list[@]}"
# 1 3 6

A very long variable list_accumulation_internal_list is used to avoid name clash with outer varitables.

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