Bash Programming
1. Indexed Arrays
instruments=("piano" "flute" "guitar" "oboe")
We can alternatively use declare -a
followed by the array name to explicitly define it.
declare -a instruments=("piano" "flute" "guitar" "oboe")
Array values can also be set by index. Let’s insert trumpet
at the 6th6th index in our instruments
array.
instruments[6]="trumpet"
Let’s take a look at all of the elements in our array using the @
symbol.
@
symbol.echo ${instruments[@]}
2. Associative Arrays
You can create associative arrays to specify two values instead of just one. We can do this by using declare -A
followed by the array name.
To use or access a key with spaces, it must be surrounded in quotes.
echo ${student[name]} is majoring in ${student["area of study"]}.
Discovery 1
**2. Check if the file thisisascript.txt
has been modified since it was last read and echo the results.
💡 Solution: The -N
option returns True if a specified file has been modified since it was last read. [ -N thisisascript.txt ]; echo $?
Discovery 2
**1. Assign an indexed array called tempo
containing the values below:
We can do this a few ways. We can declare the array first, then populate each index explicitly.
We can also assign items to the array using compound assignments
tempo=(Lento, Largo, Adagio, Andante, Moderato, Vivace, Presto)
**2. Display all of the elements of tempo
quoted separately, then display the elements quoted as a single string.
💡 Solution
We can display all elements of the array quoted separately using @
The *
character displays the elements as a single quote.
**3. Display indices 2 through 5 of the tempo
array.
💡 Solution
We can print a range of indices using the format below.
**4. Declare an associative array called BPM
containing the following string indices and values.
We can use declare -A
to declare an associative array.
**5. Add the following string:value pair to the beginning of the BPM
array.
We can add this item to the beginning of the array using the following syntax.
💡 NOTE : -a is for indexed while -A is for associative
Last updated