Intermediate Bash - Arrays

Question Click to View Answer

Assign the variable my_life to an array with the elements train, ride, and home.

my_life=(train ride home)

Print the first element of the following array:

feelings=(sleepy tired)
echo ${feelings[0]}

Bash arrays are zero-indexed.

Create an array called dogs and add the value "fido" at position 100.

dogs[100]=fido

Print every element of the hockey_stuff array:

hockey_stuff=(helmet gloves stick)
echo ${hockey_stuff[@]}

Find the number of elements in the junk array:

junk=('crap' 'more crap' 'so much stuff')
echo ${#junk[@]}

Find all the indices that are used in the jump_around array:

jump_around[1]='i came'
jump_around[45]='to get down'
jump_around[88]='get down'
echo ${!jump_around[@]}

Add the elements j and k to the end of the funny array.

funny=(l o l)
# add the elements
funny+=(j k)

# verify the elements have been added
echo ${funny[@]}

Get the last element from the arr array:

arr=(snake rat cat dog)
arr[100]=blah
echo ${arr[@]:(-1)}

Sort the following array:

scattered=(z a x b)
for i in ${scattered[@]}; do
  echo $i
done | sort

Delete the wu_tang array:

wu_tang=(rza gza method_man)
unset wu_tang