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.
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.
sh is the same as bash. But, if not, then associative arrays are not supported. In this case, simply use numerically indexed arrays. If you wish to use keywords, assign numeric values to the keywords, and they can still be used as indexes.sh by default, you can still use bash in a script, with the #!/bin/bash syntax on the first line of the script. If your system does not have /bin/bash, then you can download and install bash into /usr/local/bin/bash and invoke it with #!/usr/local/bin/bash in the first line of the script.ls -l /bin/*shIf 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'
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"
echo "${results[*]}"will print? Also -- is this Bash? Which version?bashcan you useksh? Most of the answers below will work with even the old version ofksh. change the top line of your script to#!/bin/ksh(or the correct path toksh). Good luck.