Home > Net >  Storing items generated in a loop in a variable or array without using files
Storing items generated in a loop in a variable or array without using files

Time:04-15

I am doing this within github actions and I have a for loop

items="item1 item2 item3"
version=$(date  %s)

for item in $items; do 
    # some code
    echo "category/$item:$version" | cut -d '/' -f2- | tee -a list_all_items.txt;   
done

And this is fine. I get the output I need in that text file but I am trying to avoid working with text files, and I don't know how to store the output in some kind of variable/array I can later re-use.

I really need to store whatever's in list_all_items.txt in a variable, and I can do that outside the for loop, but is it possible to achieve it within for loop?

EDIT: I edited the script to be reproducible.

The output (list_all_items.txt):

item1:1649946431 item2:1649946431 item3:1649946431

etc. So it's a string with values separated by space.

CodePudding user response:

Assuming the array capture is to contain the output, why not try something like ...

declare capture=() ; for item in $items; do 
    # some code
    capture =( "$(echo "main/$category:${{ env.VERSION}}" | cut -d '/' -f2-)" )   
done

... and thereafter ...

local l ; for l in "${capture[@]}" ; do
  .
  .
  .
done

FWIW, I fail to see the point of the loop if the $item variable isn't used ... as shellcheck would have told you.

CodePudding user response:

Several ways to do this depending on OP's expected result ...

[worse] Capturing the output into a single variable, with embedded linefeeds:

$ myvar=$(for item in $items; do echo "main/category/$item:$version" | cut -d '/' -f3-; done)          
$ typeset -p myvar
declare -- myvar="item1:1649947065
item2:1649947065
item3:1649947065"

[worse] Capturing the output into a single variable, linefeeds converted to spaces:

$ myvar=$(for item in $items; do echo "main/category/$item:$version" | cut -d '/' -f3-; done | tr '\n' ' ')
$ typeset -p myvar
declare -- myvar="item1:1649947065 item2:1649947065 item3:1649947065 "

Eliminating the subprocess call and the unnecessary cut ...

[better] Capturing the output into a single variable with a space between strings:and having the for loop append the text to the end of a variable:

$ delim=""
$ myvar=""

$ for item in $items
do
    myvar="${myvar}${delim}${item}:${version}"
    delim=" "
done

$ typeset -p myvar
declare -- myvar="item1:1649947065 item2:1649947065 item3:1649947065"

[best] Capturing the output into an array:

$ myarr=()

$ for item in $items
do
    myarr =( "${item}:${version}" )
done

$ typeset -p myarr
declare -a myarr=([0]="item1:1649947944" [1]="item2:1649947944" [2]="item3:1649947944")
  • Related