Reputation: 23
results=
results['startlogdate']="Start time"
results['endlogdate']="$finish_time"
echo "${results[*]}"
I am trying to initialise the array and adding the value to array and echo the array. The code above is my attempt.
Upvotes: 0
Views: 1170
Reputation: 2346
In bash scripts, there are two kinds of arrays: numerically indexed and associatively indexed.
Depending on the version of your shell, associatively indexed arrays might not be supported.
Related to the example in your question, the correct syntax to obtain the values of the array, each as a separate word, is:
"${results[@]}"
To get the keys of the associative array, do:
"${!results[@]"
The script below demonstrates the use of an associative array. For more details, see the Arrays
section in the bash
manpage.
#!/bin/bash
# tst.sh
declare -A aa
aa[foo]=bar
aa[fee]=baz
aa[fie]=tar
for key in "${!aa[@]}" ; do
printf "key: '%s' val: '%s'\n" $key "${aa[$key]}"
done
echo "${aa[@]}"
exit
Here is the output:
$ bash tst.sh
key: 'foo' val: 'bar'
key: 'fee' val: 'baz'
key: 'fie' val: 'tar'
tar bar baz
Finally, I've made available my library of array functions (aka "lists"), which I've been using for many years to make managing data in arrays easy.
Check out https://github.com/aks/bash-lib/blob/master/list-utils.sh
Even if you choose not to make use of the library, you can learn a lot about arrays by reading the code there.
Good luck.
Upvotes: 1
Reputation: 44
finish_time=`date`
results[0]="Start time"
results[1]="$finish_time"
echo ${results[@]}
Output: Start time Wed Jan 8 12:25:14 IST 2014
Number of elements: echo ${#results[@]}
Arrays in bash are zero indexed, so ${results[0]} will be "Start time" and ${results[1]} will be "Wed Jan 8 12:25:14 IST 2014"
Upvotes: 0
Reputation: 1037
If want to use array in bash. you will be able to do in two ways.
Declare an array in bash.
declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora');
echo ${Unix[0]} # Prints the first element
echo ${Unix[*]} # prints all the elements of an array
Use directly (i.e) without declare.
Unix[0]='Debian';Unix[1]='Red hat'
Upvotes: 0