S
S
Seeker2021-06-22 09:56:13
bash
Seeker, 2021-06-22 09:56:13

How to assign the value of an element of a string array in bash?

The question is, there are string arrays in bash, you can assign an array element through array["$i"]=. For example, I do so that the lines from the array.list file are written to the string array array, and then displayed ... and it does not work. Where is the mistake?

#!/bin/bash

i=1
cat array.list | while read str
do
   array["$i"]="$str"
   i=$(($i+1))
done
echo ${array[@]}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Bereznikov, 2021-06-22
@gdt

Well, I did a Google search for you:
bash set array element
Enjoy:

  • How to use arrays in bash script
  • How to reassign new values ​​to array elements?

I'm not a real welder, but I'll venture a guess that adding a string by type
declare -a array
before the loop might help.

S
Saboteur, 2021-06-22
@saboteur_kiev

In your case cat array | while runs the entire while block in a separate shell process, and naturally the result will not be returned to the parent process, dying along with the end of the loop and the child process.
Do like this:

#!/bin/bash

i=1
while read str
do
   array["$i"]="$str"
   i=$(($i+1))
done <array.list 
echo ${array[@]}

X
xotkot, 2021-06-22
@xotkot

you can drive lines from a file into an array much easier:

x="$IFS";IFS=$'\n';array=(`cat array.list`);IFS="$x"

specific to your choice, you can use the lastpipe option to execute the last pipe command in the current shell:
i=1
shopt -s lastpipe
cat array.list | while read str
do
   array["$i"]="$str"
   i=$(($i+1))
done
shopt -u lastpipe
echo ${array[@]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question