当涉及到带空格的变量时,有没有办法使 bash 循环正常工作?

Is there a way to make bash loops work properly when variables with spaces are involved?

在此先感谢您的帮助!

我正在编写一段代码以在 Mac 上自动设置 Homebrew,但我遇到了问题。 这是我目前拥有的代码:

#!/usr/bin/env bash

brew="
app1 test
app2
app3
"

for i in $brew; do
    echo brew install $i
done

我的预期输出是这样的:

brew install app1 test
brew install app2
brew install app3

但是,脚本的实际输出是这样的:

brew install app1
brew install test
brew install app2
brew install app3

我试过在我的循环中引用“i”和“$brew”命令但没有结果。如果有人有任何可能的解决方案,请分享!谢谢!

您需要使用数组。

如果您需要包含空格的数组元素,请引用这些元素:

brew=("app1 test" app2 app3)

遍历数组元素时,也使用引号来保留其中的空格:

for i in "${brew[@]}"; do
    echo brew install $i
done

另请参阅:Loop through an array of strings in Bash?