others-how to echo/display bash variable or environment variable in Linux/MacOS system with bash scripts ?

Problem

When we want to echo or display variables in Linux/MacOS systems with terminal command as follows:

my.sh

echo 'start build $1 with repo $2, click to start ...'

If we execute this my.sh,we got the following string:

➜  bswen-springboot23 git:(main) ✗ ./my.sh app7 myrepo
start build $1 with repo $2, click to start ...

Why did this happen? How to show variable in bash scripts?

Environment

  • Linux
  • MacOS
  • Unix

Reason

You should use double quotes instead of single quotes to show variable values in bash scripts.

According to likso’s answer in this content,

If you’re referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

Single quotes does have its pros:

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

Solution

Change the script , use double quotes to enclose the string with variables:

my.sh

echo "start build $1 with repo $2, click to start ..."

If we execute this my.sh,we got the following string:

➜  bswen-springboot23 git:(main) ✗ ./my.sh app7 myrepo
start build app7 with repo myrepo, click to start ...

It works!

-->