如何在macOS的Bash中将softwareupdate --list的输出保存为变量?
Solution for Capturing Full
softwareupdate --list Output into an Array Issues with Your Original Approach
Your command fails to capture the full output for two key reasons:
- Missing stderr capture:
softwareupdate --listsends some output (like the "No new software available" line) to stderr instead of stdout. The$(...)substitution only captures stdout, so those lines are lost. - Word-based splitting: Assigning to an array with
updates=( $(command) )splits the output into individual words (using whitespace as the delimiter), not entire lines. Blank lines are ignored, and lines with spaces get split into multiple array elements.
Correct Method to Capture Full Output
Step 1: Capture Both Stdout and Stderr, Read Lines into Array
Use readarray (or mapfile, its equivalent) to read each line of the command's output (including stderr) into an array. This preserves line breaks and keeps each line as a single array element.
readarray -t updates < <(softwareupdate --list 2>&1)
2>&1redirects stderr to stdout, ensuring all output is captured.-tremoves trailing newline characters from each line.- The process substitution
<(...)feeds the command's output directly intoreadarray.
Step 2: Print the Full Captured Output
To display the entire output correctly, use printf to print each array element on a new line:
printf '%s\n' "${updates[@]}"
"${updates[@]}"expands to each element of the array, preserving spaces and special characters in individual lines.%s\nensures each element is printed followed by a newline, matching the original command's output format.
Alternative for Older Bash Versions
If readarray isn't available (bash < 4.0), use a while loop to read lines into the array:
updates=() while IFS= read -r line; do updates+=("$line") done < <(softwareupdate --list 2>&1)
Then print the output with the same printf command as above.
内容的提问来源于stack exchange,提问作者user2416805
相关产品推荐
相关产品推荐

