Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this bash function prints only first word of whole string?

I'm trying to create function that will print message bound to variable in certain color. The message variable is passed as argument of this function. The problem is that I'm getting only text up to first space (only first word of message). My script looks like this:

#!/usr/bash

lbGREEN='\e[1;92m'
NC='\e[0m'

normalMessage="Everything fine"

echo_message() {

    echo -e  ${lbGREEN}$1${NC}

}

echo_message $normalMessage 

My output is:

Everything
like image 348
s-kaczmarek Avatar asked Oct 19 '25 13:10

s-kaczmarek


1 Answers

As Inian pointed out in comments, your problem is unquoted variable expansion

echo_message $normalMessage 

becomes

echo_message Everything fine

once the variable expands, meaning that each word of your input string is getting read in as a separate argument. When this happens $1=Everything and $2=fine.

This is fixed by double-quoting your variable, which allows expansion, but will mean the result of the expansion will still be read as one argument.

echo_message "$normalMessage"

becomes

echo_message "Everything fine"

Like this $1=Everything fine

In the future, I recommend using https://www.shellcheck.net/, or the CLI version of shellcheck, it will highlight all kinds of common bash gotcha's, included unquoted expansion.

like image 141
Will Barnwell Avatar answered Oct 22 '25 03:10

Will Barnwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!