1

I am trying to add an element to a bash array. I looked at this question and tried to follow its advice.

This is my code:

selected_projects=()
for project_num in ${project_numbers[@]}; do
  selected_project=${projects[$project_num]}
  echo "selected project: $project_num $selected_project"
  $selected_projects+="$selected_project"
done

When I do this, I get an error:

line 88: +=someProject: command not found

I tried many different alternatives to that line with lots of parenthesis and dollar signs, but I cannot figure out what I'm doing wrong and what it should be. Any ideas?

Thanks!

chama
  • 113
  • 4

2 Answers2

4

Use

selected_projects+="$selected_project"

instead of

$selected_projects+="$selected_project

Variable assignment in bash never contains $ at the beginning of variable name.

MichalH
  • 2,379
3
selected_projects=()
$selected_projects+="$selected_project"

Variable assignments in the shell don't use the $ sign on the left hand side, it's only used when the value of the variable is expanded. This includes appending with +=. Your other assignment was correct.

In addition, since you've initialized selected_projects as an array, you probably want to use it such. To append a value to an array, you need to use the parenthesis in the appending assignment too. So, this would add a new element to selected_projects:

selected_projects+=("$selected_project")

Without the parenthesis, the assignment works like an unindexed reference to the array: it accesses the element with index 0. E.g. this prints foobar foobar:

a=(); a+=foo; a+=bar; echo ${a[0]} $a
ilkkachu
  • 138,973