2

I have this function:

cyan=`tput setaf 6`
reset=`tput sgr0`
function Info()
{
    echo "${cyan}$1${reset}"
}

And I use it in my other scripts as simple as Info some message.

However, when I use it to print all items of an array, it only prints the first item:

Info "${ArrayVariable[@]}" # this only prints the first item

echo ${ArrayVariable[@]}" # this prints all of them

How can I preserve all of the variables when using this syntax and this function?

3
  • 1
    "$1" points only to the first parameter in a parameter list, and I think also to the first element in the array. Try with "$@" in the function.
    – sudodus
    May 21, 2022 at 10:31
  • 1
    @sudodus Using "$*" would be more appropriate here as what is needed is a single string, not a list.
    – Kusalananda
    May 21, 2022 at 11:39
  • 1
    OK @Kusalananda, I'm learning ...
    – sudodus
    May 21, 2022 at 12:06

1 Answer 1

3

In your function, $1 expands to the first argument. When you call your function using

Info some message

... then the value of $1 is some, while the value of $2 is message.

You can keep your function as it is and instead call it with

Info 'some message'

or

Info "$mymessage"

or

Info "${mymessagearray[*]}"

Quoting the whole message ensures that the message string is the first argument and that it, therefore, will be available in $1 inside the function.

In the case of the array mymessagearray above, using [*] in place of [@] gives you a single string with all the elements of the array delimited by the first character of $IFS (a space by default). This single string is quoted (the double quotes in the code), so it's all delivered to your function in $1.

The other way to do it is to expand $* in the string you are printing. The value "$*" is the value of all arguments delimited by the first character of $IFS (a space by default).

Info () {
    echo "$cyan$*$reset"
}

Personally, I would opt for using quotes around the arguments instead, ensuring that the message is printed as is, without splitting it on whitespace or performing filename globbing on it (which would happen if you called the function with an unquoted value).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .