0

I have a simple function that colors its input argument.

color_text_red()
{
    echo -e "\033[0;91m$1\033[0m"
}

Now, I have 2 variables START_COUNT and STOP_COUNT that have some value.

START_COUNT="1"
STOP_COUNT="2"

I would like to construct the string [1, 2] where 1, 2 is colorized. So, I did this :

out_res="${START_COUNT}, ${STOP_COUNT}"
echo "[$(color_text_red $out_res)]"

Sadly, this outputs only [1,].

Why $STOP_COUNT is missing ?

2
  • color_text_red $out_res - because you are passing two arguments to the function. Commented Oct 21, 2019 at 10:45
  • It is only ONE variable $out_res. How can we achieve this otherwise ? Commented Oct 21, 2019 at 10:47

1 Answer 1

1

Observe:

f() {
  echo "First argument: $1"
  echo "Second argument: $2"
}
var="a b"
f $var

It will output:

First argument: a
Second argument: b

The unquoted variables are splitted using whitespace characters (tabs, newlines and spaces) and then passed to the function (that is, assuming IFS variable is the default or unset). So, if the variable has spaces, it will be splitted. That's why it is adviced all over stackoverflow to quote your variables.

You should quote your variable expansions if you want to pass only a single argument to the function:

out_res="${START_COUNT}, ${STOP_COUNT}"
echo "[$(color_text_red "$out_res")]"

Rule of a thumb: always type " in front and after $ expansions, ex. "$var" or "$(echo 1)" or "${var## }".

Some additional read: bash manual word splitting, riptutorial word splitting.

Sign up to request clarification or add additional context in comments.

1 Comment

Aha ! It is all about quoting variables ! Now I see. Thanks @Kamil :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.