0

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!

3
  • 1
    selected_projects+="$selected_project" instead of $selected_projects+="$selected_project" – MichalH Jun 19 '20 at 19:25
  • @MichalH This worked! Please leave this as an answer so I can accept it. Thank you!!!! – chama Jun 19 '20 at 19:27
  • @KamilMaciorowski That really is funny! – chama Jun 19 '20 at 19:35
4

Use

selected_projects+="$selected_project"

instead of

$selected_projects+="$selected_project

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.