1

I found a script written in Bash that automate the installation of packages and software on a new Mac.

This is part of the script:

# helpers
function echo_ok() { echo -e '\033[1;32m'"$1"'\033[0m'; }

PACKAGES=(
    vim
    zsh
    tree
    git
)

echo_ok "Installing packages..." 
brew install "${PACKAGES[@]}"

The script correctly install all of the packages listed in the array.

For testing purpose, I modified the line

brew install "${PACKAGES[@]}"

into

echo_ok "${PACKAGES[@]}"

As output I get only the first item of the array (vim).

However, if I use

echo "${PACKAGES[@]}"

I get all the elements of the array.

It looks like the problem is passing the array in the helper function. If I'm not mistaken, '\033[1;32m' and '\033[0m'; have to do with the colours of the text and "$1" is the parameter passed into that helper function. Are the double quotes important? Because I see double quote also around "${PACKAGES[@]}".

I'm not really sure what I'm doing wrong and why I'm not getting the entire content of the array as when used with brew install "${PACKAGES[@]}".

3
  • 2
    "$1" should be "$@" in echo_ok() Commented Dec 18, 2020 at 14:46
  • @Inian: That is not the only issue as echo -e with $@ will not print each element with newline Commented Dec 18, 2020 at 14:50
  • I don't see OP's intentions being wanting to print it on new line. They seem to be testing the arguments to brew install in which case the arguments need to be on the same line Commented Dec 18, 2020 at 14:51

1 Answer 1

1

Change your function to this i.e. printf instead of echo -e and use "$@" instead of "$1" like this:

echo_ok() {
   printf '\033[1;32m%s\033[0m\n' "$@"
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.