[Unix-Linux] Shell Scripting - Arrays

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the Unix/Linux course!


Arrays

Arrays

Simple Declaration

type='article'  #simple declaration

echo "I found 10 $type" #the grammar is incorrect
echo "I found 10 "$type"s"  #ugly fix
echo "I found 10 ${type}s"  #great solution when working with array


Declaration of an (Numeric) Array

  • An array is a set of values delimited by a pair of parenthesis.
  • Each item is accessed by a zero-based index.
profs=()  #empty array
profs=('Mehrdad')  #array with a single item

Working with Items

profs[1]='Narendra'
#Inserts the value 'Narendra' at position 1 in the profs array.

profs+=('Ilia' 'Arben')
#Appends the values 'Ilia' and 'Arben' at the end of the profs array.

profs[3]='Hao'
#Replaces the value at position 3 in the profs array with 'Hao'.

echo "${profs[3]}"
#Prints the value at position 3 in the profs array, which is 'Hao'.

echo "${#profs[@]}"
#Prints the number of items in the profs array using the ${#profs[@]} syntax.

unset profs[2]
#Deletes the item at position 2 in the profs array.

Iterating an Array

count=1  #will be used to number each line

echo 'All profs: '
for prof in "${profs[@]}"
do
  echo "$count: $prof"
  (( count++ ))
done


Declaration of an Associative Array

  • An associative array is declared differently.
  • Each item is accessed by a key.
  • A collection of key-value pairs. Similar to a python dictionary.
declare -A courses=()  #empty array

declare -A courses=   #array with five items
(
  [COMP100]="Programming 1"
  [COMP213]="Web Interface Design"
  [COMP123]="Programming 2"
  [COMP125]="Client-Side Scripting"
  [COMP120]="Software Engineering Fundamentals"
)

Working with Pairs

courses[COMP301]='Linux Operation System'
#Inserts a new key-value pair into the courses array, where the key is COMP301 and the value is 'Linux Operation System'.

echo " ${courses[@]}"
#Prints all the values stored in the courses array.

echo " ${!courses[@]}"
#Prints all the keys of the courses array.

echo " ${courses[COMP100]}"
#Prints the value associated with the key COMP100 in the courses array.

echo " ${#courses[@]} "
#Prints the number of items (key-value pairs) in the courses array.

unset courses[COMP213]
#Deletes the key-value pair from the courses array where the key is COMP213.

Iterating an Array

if [[ -v courses[$key] ]]   #checks if key exists in courses array
then
  echo "$key is present"
fi

for code in "${!courses[@]}"
do
  echo "key: $code - value: ${courses[$code]}"
done




Back to Top

See other articles in Category Unix-Linux

Leave a comment