BASH:从函数返回数组输出

时间:2019-12-12 09:06:33

标签: bash

我目前正在使用bash脚本,该脚本从xml文档中读取并在假日返回值city。

xmlconfig="/home/scripts/sample.xml"
dt=$(date +'%Y%m%d')

cty=$(get-holiday-country "$dt" "$xmlconfig")
echo "This are the cities:"
echo "$cty"

get-holiday-country()
{
        declare -a arr
        for q in `echo 'cat /holiday[@date="$1"]/country/@value' | xmllint --shell "$2" | awk -F\" '/=/ { print $2; }'`
        do arr+=("$q")
        done
}

但是,我在创建的函数中得到了一个空值,并且仅在运行for循环时它就起作用了。

for q in `echo 'cat /holiday[@date="$1"]/country/@value' | xmllint --shell "$2" | awk -F\" '/=/ { print $2; }'`; do echo "$q"; done

您能帮我找出我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

示例XML文件:

<holiday date="20191225">
    <country value="US">
        <day value="today">
            <job name="USJOB1"></job>
            <job name="USJOB2"></job>
            <job name="USJOB3"></job>
        </day>
    </country>
    <country value="PH">
        <day value="today">
            <job name="PHJOB1"></job>
            <job name="PHJOB2"></job>
            <job name="PHMJOB3"></job>
        </day>
    </country>
</holiday>

我对收到的评论进行了更改,以下是最终代码。

get-holiday-country()
{
        arr=()
        for q in `echo "cat /holiday[@date="$1"]/country/@value" | xmllint --shell "$2" | awk -F\" '/=/ { print $2; }'`
        do
                arr+=("$q")
        done
        echo ${arr[*]}
}

xmlconfig="/home/scripts/sample.xml"
dt=$(date +'%Y%m%d')

cty=$(get-holiday-country "$dt" "$xmlconfig")
echo "These are the cities:"
echo "$cty"