shell脚本中的奇怪数组输出

mo49yndu  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(142)

从文件中提取的内容被分离出来并存储在数组中,并使用循环打印内容。只打印最后一个元素很奇怪。我给你看我的代码。我该如何解决这个问题?
[配置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 !!!!
mqkwyuun

mqkwyuun1#

你可以使用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

相关问题