如何设置引用多层变量的Shell数组并实现预期输出?
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 invar. SinceMASTERVARcontainsblahblah2blah3(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

