why do I get an error 'invalid arithmetic oper

2020-04-22 01:27发布

问题:

I am trying to parse yaml to Json. and I'd like to set the array that has string index.

when I v tried it I got an error

here is my source and error

keys=$(echo $ci_json | jq 'keys')
key_array=($keys)
ARR=()

for raw_key in ${key_array[@]}; do
        if [ $raw_key = '[' -o $raw_key = ']' ]; then
                continue;
        else
                key=$(echo $raw_key | sed -e 's/"//g' -e 's/,//g')
                value=$(echo $ci_json | jq .$key)$'\t'
                ARR[$key]=$value
        fi
done

Error : localhost.localdomain: syntax error: invalid arithmetic operator (error token is ".localdomain")

This error appeared at "ARR[$key]=$value"

anybody helps me?

This is ma key list :

APP_TYPE APP_USE ASSETS_NO ASSETS_STAT ASSETS_TYPE BIZ_GROUP BIZ_L1 BIZ_L2 CI_COMMENT CI_NO CI_OWNER CI_PARENT CPU_CLOCK CPU_CORE CPU_MODEL CPU_NUM CPU_VENDOR DB_ADMIN1 DB_ADMIN2 DEV_ADMIN DEV_ADMIN2 DISUSE_DATE ENTER_DATE EXPIRE_DATE HDD_MODEL HDD_NUM HDD_TYPE HDD_VENDOR HDD_VOL HOLE_NO HOSTNAME IDC INTO_DATE MAINT_CORP MAINT_DATE MEM_MODEL MEM_NUM MEM_VENDOR MEM_VOL MODEL NIC1_IP NIC1_MAC NIC1_PORT NIC1_SW NIC2_IP NIC2_MAC NIC2_PORT NIC2_SW NIC_MODEL NIC_VENDOR OOB_IP OOB_MAC OOB_PORT OOB_SW OS_ARCH OS_KERNEL OS_NAME RACK RACK_NO RAID_CACHE RAID_FIRM RAID_MODEL RAID_NO RAID_VENDOR REPRESENT SC_ADMIN SC_CATEGORY SC_DEPT SC_TYPE SEND_DATE SERIAL_NO SERVER_CLASS SIM SPEC_CODE SVC_GROUP SVC_L1 SVC_L2 SYS_ADMIN SYS_ADMIN2 UNIT USE_DESC VENDOR VM_CLASS VM_TYPE assignType

回答1:

 Error : localhost.localdomain: syntax error: invalid arithmetic operator (error token is ".localdomain")

This happens on ARR[$key]=... when ARR is an indexed array (not associative) and the value of key is localhost.localdomain. Indexed arrays should use numeric subscripts, not arbitrary strings.

If you want to use string indexes with ARR, you must declare it as an associative array, which is supported as of Bash 4:

declare -A ARR


回答2:

If you want to use non-numeric keys, use an associative array instead of a normal array. You have to declare it, though, so replace

ARR=()

with

declare -A ARR


标签: bash shell