Array declaration in shell script

Hi All,

I am using below script in Linux to find the files, But same script is not working in Solaris 10 and AIX 7.

declare -A hash=( ["abc.conf"]="test1" ["xyz.xml"]="test2"  )
var1=$(find / \( -name abc.conf -o -name xyz.xml \) -print 2>&1)

for j in $var1
do
    file_name=$(echo "$j" |awk -F/ '{ print $NF }')
    echo -e "{\"'"${hash["$file_name"]}"'\":\"'"$j"'\"}"
done

Error : Syntax error: invalid arithmetic operator (error token is ".conf")

Can someone please help

The script is using bash 4 syntax. If you want to use the same syntax on Solaris 10 and AIX7, you need to make sure it is installed there as well. If that is not the case, you would need to write code that is a common denominator on all OS'es.

POSIX syntax would a good approach, since that is what all these OS'es adhere to. All three have a posix shell, which is usually /bin/sh. On Solaris its path is /usr/xpg4/bin/sh.
But you cannot use arrays and echo -e cannot be used. See below for an alternative.

Another option is to rewrite to Kornshell 93
On Solaris its path is /usr/dt/bin/dtksh
On AIX and Linux this is /usr/bin/ksh93
Also you would need to use typeset instead of declare
and replace

echo -e "{\"'"${hash["$file_name"]}"'\":\"'"$j"'\"}"

with

printf "{\"'%s'\":\"'%s'\"}\n" "${hash["$file_name"]}" "$j"

or you can use a scripting language like Perl

--
The error message that you see is on Solaris is coming from an ancient shell (the Bourne shell), which on Solaris is /bin/sh and which does not recognize the $( ... ) command substitution, but only understands `...`

5 Likes