shell 脚本中的奇怪数组输出

Weird array output in shell script

将文件中提取出来的内容分开存放在一个数组中,使用循环打印内容。只打印最后一个元素很奇怪。我会告诉你我的代码。 我该如何解决这个问题?

[config.json]

{ 
  "id": "hello",
  "passwd": "1234",
  "languageList": ["ko", "en"]
}

[test.sh]

# BEFORE_CONFIG and AFTER_CONFIG have same code
BEFORE_CONFIG=~/workspace/env/config.json
AFTER_CONFIG=~/workspace/config/config.json

BEF_LANG=$(grep "\[" ${BEFORE_CONFIG} | tr -d '\[' | tr -d '\]' | tr -d '"' | tr -d ' ' | cut -d ":" -f2)
AF_LANG=$(grep "\[" ${AFTER_CONFIG} | tr -d '\[' | tr -d '\]' | tr -d '"' | tr -d ' ' | cut -d ":" -f2)

echo "before lang :: ${BEF_LANG}"
echo "after lang :: ${AF_LANG}"


IFS=',' read -r -a AF_LANG_LIST <<< "$AF_LANG"

echo "after lang list print >> ${AF_LANG_LIST[@]}"
echo "list length >> ${#AF_LANG_LIST[@]}"


for element in ${AF_LANG_LIST[@]}
do
            echo "${element}"
            echo "This language !!! ${element} !!! print !!!!"
done

[结果]

$ source tesh.sh

before lang :: ko,en
after lang :: ko,en
after lang list >> ko en
list length >> 2
ko
This language !!! ko !!! print !!!!
en
 !!! print !!!!!! en   # expect result → This language !!! en !!! print !!!!

您可以使用jq正确解析json,并提取languageList

cat ~/workspace/env/config.json|jq .languageList[] -r|xargs

这将输出:

ko en

稍后可以在脚本中使用

尝试用 trcut 解析 JSON 很容易出错。

这是您的脚本示例:

#!/bin/bash
# BEFORE_CONFIG and AFTER_CONFIG have same code
BEFORE_CONFIG=~/workspace/env/config.json
AFTER_CONFIG=~/workspace/config/config.json

BEF_LANG=$(grep "\[" ${BEFORE_CONFIG} | tr -d '\[' | tr -d '\]' | tr -d '"' | tr -d ' ' | cut -d ":" -f2)
#AF_LANG=$(grep "\[" ${AFTER_CONFIG} | tr -d '\[' | tr -d '\]' | tr -d '"' | tr -d ' ' | cut -d ":" -f2)

AF_LANG=$(cat ${BEFORE_CONFIG}|jq .languageList[] -r|xargs)

echo "before lang :: ${BEF_LANG}"
echo "after lang :: ${AF_LANG}"

# you do not need this
#IFS=',' read -r -a AF_LANG_LIST <<< "$AF_LANG"

#echo "after lang list print >> ${AF_LANG_LIST[@]}"
#echo "list length >> ${#AF_LANG_LIST[@]}"


for element in ${AF_LANG[@]}
do
            echo "${element}"
            echo "This language !!! ${element} !!! print !!!!"
done