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

如何在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 --list sends 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>&1 redirects stderr to stdout, ensuring all output is captured.
  • -t removes trailing newline characters from each line.
  • The process substitution <(...) feeds the command's output directly into readarray.

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\n ensures 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 23:42:27