Introduction to Bash Scripting
Alex Scriven
Data Scientist
Two types of arrays in Bash:
In Python: my_list = [1,3,2,4]
In R: my_vector <- c(1,3,2,4)
Creation of a numerical-indexed can be done in two ways in Bash.
1. Declare without adding elements
declare -a my_first_array
2. Create and add elements at the same time
my_first_array=(1 2 3)
Remember - no spaces around equals sign!
Commas are not used to separate array elements in Bash:
This is not correct:
my_first_array=(1, 2, 3)
This is correct:
my_first_array=(1 2 3)
array[@]
. Though do note, Bash requires curly brackets around the array name when you want to access these properties.my_array=(1 3 5 2)
echo ${my_array[@]}
1 3 5 2
#array[@]
echo ${#my_array[@]}
4
Accessing array elements using square brackets.
my_first_array=(15 20 300 42)
echo ${my_first_array[2]}
300
Set array elements using the index notation.
my_first_array=(15 20 300 42 23 2 4 33 54 67 66)
my_first_array[0]=999
echo ${my_first_array[0]}
999
$
when overwriting an index such as $my_first_array[0]=999
, as this will not work.Use the notation array[@]:N:M
to 'slice' out a subset of the array.
N
is the starting index and M
is how many elements to return.my_first_array=(15 20 300 42 23 2 4 33 54 67 66)
echo ${my_first_array[@]:3:2}
42 23
Append to an array using array+=(elements)
.
For example:
my_array=(300 42 23 2 4 33 54 67 66)
my_array+=(10) echo ${my_array[@]}
300 42 23 2 4 33 54 67 66 10
What happens if you do not add parentheses around what you want to append? Let's see.
For example:
my_array=(300 42 23 2 4 33 54 67 66)
my_array+=10
echo ${my_array[@]}
30010 42 23 2 4 33 54 67 66
The string 10
will just be added to the first element. Not what we want!
bash --version
in terminalIn Python:
my_dict = {'city_name': "New York", 'population': 14000000}
In R:
my_list = list(city_name = c('New York'), population = c(14000000))
You can only create an associative array using the declare syntax (and uppercase -A
).
You can either declare first, then add elements or do it all on one line.
Let's make an associative array:
declare -A city_details # Declare first
city_details=([city_name]="New York" [population]=14000000) # Add elements
echo ${city_details[city_name]} # Index using key to return a value
New York
Alternatively, create an associative array and assign in one line
declare -A city_details=([city_name]="New York" [population]=14000000)
Access the 'keys' of an associative array with an !
echo ${!city_details[@]} # Return all the keys
city_name population
Introduction to Bash Scripting