You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置引用多层变量的Shell数组并实现预期输出?

How to Properly Create Your Shell Array

The correct way to build your ULTIMATEMASTERVAR array so each element holds the full value of MASTERVAR and ULTIMATEVAR is to wrap each variable expansion in double quotes:

ULTIMATEMASTERVAR=("${MASTERVAR}" "${ULTIMATEVAR}")

Why Your Previous Tries Failed

Let's go through each attempt to see what went wrong:

  • ULTIMATEMASTERVAR=(${MASTERVAR} ${ULTIMATEVAR}):
    This works for your current values (since they have no spaces or special characters), but it's fragile. The shell splits unquoted variables into words based on whitespace, and expands glob patterns like *. If your variables ever included spaces, this would split them into multiple array elements instead of keeping them intact.

  • ULTIMATEMASTERVAR=('${MASTERVAR}' '${ULTIMATEVAR}'):
    Single quotes prevent variable expansion entirely. This means your array will have elements that are literally the strings ${MASTERVAR} and ${ULTIMATEVAR}, not the values those variables store.

  • ULTIMATEMASTERVAR=(${!MASTERVAR} ${!ULTIMATEVAR}):
    The ${!var} syntax is for indirect expansion—it looks for a variable whose name is stored in var. Since MASTERVAR contains blahblah2blah3 (not a valid variable name), this just returns empty strings, leaving your array with no meaningful content.

Testing the Solution

Here's the full working code:

VARA=('blah')
VARB=('blah2')
VARC=('blah3' 'alt_blah3')
MASTERVAR=${VARA}${VARB}${VARC[0]}
ULTIMATEVAR=${VARA}${VARB}${VARC[1]}
ULTIMATEMASTERVAR=("${MASTERVAR}" "${ULTIMATEVAR}")

# Verify the results
echo ${ULTIMATEMASTERVAR[0]}  # Output: blahblah2blah3
echo ${ULTIMATEMASTERVAR[1]}  # Output: blahblah2alt_blah3

This will give you exactly the behavior you want, and it's robust enough to handle spaces or special characters in your variables later on.

内容的提问来源于stack exchange,提问作者Caucasian Malaysian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:05