-1

and thanks in advance for your help!

I'm having an issue with a piece of code I'm writing to automate the setup of Homebrew on my Mac. Here's the code I currently have:

#!/usr/bin/env bash

brew="
app1 test
app2
app3
"

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

My expected output is this:

brew install app1 test
brew install app2
brew install app3

But, the actual output of the script is this:

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

I've tried quoting both the "i" and "$brew" commands in my loop with no results. If anyone has any potential solutions, please share them! Thanks!

1 Answers1

1

You need to use an array.

If you need array elements which include spaces, quote these elements:

brew=("app1 test" app2 app3)

When looping over the array elements, also use quotes to preserve spaces in them:

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

See also: Loop through an array of strings in Bash?

mivk
  • 13,452
  • 5
  • 76
  • 69