0

In my script I need to set values to arrays by reading from some files so instead of:

  last_price_1=$(cat ~/price/last_price_1)
  last_price_2=$(cat ~/price/last_price_2)
  ...
  last_price_10=$(cat ~/price/last_price_10)

I tried to do:

for i in {1..10}
do
  echo "check: last_price_$i"
  last_price_$i=$(cat ~/price/last_price_$i)
done
echo "check 1: $last_price_1"
echo "check 2: $last_price_2"

But gives error and not setting the value

check: last_price_1
test.sh: line 6: last_price_1=7896: command not found
check: last_price_2
test.sh: line 6: last_price_2=7898: command not found
...
check: last_price_10
test.sh: line 6: last_price_10=7868: command not found
check 1: 
check 2: 
papampi
  • 127
  • 6
  • Use `for i in {1..10}`. – Cyrus Oct 06 '19 at 15:28
  • @Cyrus it was mistyped here, not in the script – papampi Oct 06 '19 at 15:31
  • You'd have the exact same problem with `i=0; last_price_$i=1` with no loop at all. Part of building a [mre] is finding the *simplest possible code* that reproduces your problem. – Charles Duffy Oct 06 '19 at 15:32
  • ...that said, what you *should* do is make an array instead of trying to dynamically set a bunch of separate variables at all: `last_price=( ); for ((i=0; i<10; i++)); do last_price[$i]=$(<~/price/last_price_$i); done` -- later, inspecting `"${last_price[$i]}"` to get the values out. – Charles Duffy Oct 06 '19 at 15:34
  • See [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006) for a general discussion of indirect assignment and lookup, or [BashFAQ #5](https://mywiki.wooledge.org/BashFAQ/005) for a narrow discussion on the right way to use arrays. – Charles Duffy Oct 06 '19 at 15:35

0 Answers0