What the heck is ${RA[2]} in this context?

CrazedNerd

Gold Member
Gold Supporter
Joined
Mar 31, 2021
Messages
598
Reaction score
238
Credits
5,062
Code:
for person in $ME $3 Pat ${RA[2]} Sue; do

echo $person

done

Overall a pretty simple loop in bash, if i make my name that variable (ME=CrazedNerd), it will loop my name until Sue. However, ${RA[2]} seems completely random and doesn't have any functionality so far. When i run the script as described, it loops my name until sue, and bash gives me no bugs/errors. I tried assigning something to "RA" but that doesn't change it either. All i know is that RA[2] is getting grouped together by brackets.
 


gvisoc

Well-Known Member
Joined
May 29, 2020
Messages
433
Reaction score
509
Credits
4,442
The braces ${...} are a way to delimit the name of the variable for the intepreter, in context where we want to explicitly indicate what to interpret as the parameter or variable expand.

Try this:
Code:
#!/bin/bash
name="This is my name"
name_="This is not my name"

echo "$name"
echo "$name_"
echo "${name}_"

The author of the script wanted the interpreter to evaluate RA[2] and not RA, and then attach [2],
 
OP
CrazedNerd

CrazedNerd

Gold Member
Gold Supporter
Joined
Mar 31, 2021
Messages
598
Reaction score
238
Credits
5,062
Just to potentially help someone who's a bash novice like me, here's a full demonstration of a loop and array.

Script syntax:

Code:
ME=CrazedNerd
RA=( GOO-GOO GAA-GAA SIM-SIM )

for person in $ME Pat ${RA[0]} ${RA[1]} ${RA[2]} Sue; do
echo $person
done

Command line entry:

Code:
ME=CrazedNerd ; RA=( GOO-GOO GAA-GAA SIM-SIM ) ; for person in $ME Pat ${RA[0]} ${RA[1]} ${RA[2]} Sue ; do echo $person ; done

output:

Code:
CrazedNerd
Pat
GOO-GOO
GAA-GAA
SIM-SIM
Sue
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Linux.org Hosting Donations
Consider making a donation

Staff online

Members online


Top