The issue in your script is due to variable scope in Bash. In Bash, variables declared inside a while loop (or any subshell) are local to that subshell and do not persist outside of it. The while loop in your script is part of a pipeline (echo test | while ...), which runs in a subshell. As a result, the args array is modified inside the subshell, but the parent shell (where you try to print args) does not see those changes.
while loop runs in a subshell because it is part of a pipeline (echo test | while ...).args array is modified inside the subshell, but the parent shell retains its original value (empty).To ensure the args array is modified in the parent shell, avoid using a pipeline. Instead, use here-strings or process substitution to feed input to the while loop without creating a subshell.
bashargs=() while read option do args+=("$option" "$option") break done <<< "test" echo "|${args[@]}|"
Output:
text|test test|
bashargs=() while read option do args+=("$option" "$option") break done < <(echo test) echo "|${args[@]}|"
Output:
text|test test|
bashargs=() option="test" args+=("$option" "$option") echo "|${args[@]}|"
Output:
text|test test|
<<<), process substitution (< <(...)), or direct assignment to avoid subshell issues.Vibe can make mistakes. Check answers. Learn more