How to Print a Variable in the Terminal on Linux Mint

Share
In this tutorial, we'll learn how to print a variable such as an environment variable using the terminal on Linux Mint. Printing variables is useful to know what value they current hold.

To print a variable in the terminal, we echo, double quotes ("), and a dollar sign ($). If you execute the following terminal command [how?], you should see a text code representing the current language of the operating system. (> represents the shell prompt)

> echo "$LANG"
en_US.UTF-8

Above, en_US.UTF-8 is the value of the LANG environment variable. en_US refers to English language as used in the United States, and UTF-8 is the character encoding.

The echo command doesn't actually print the variable by name. Instead, it simply prints all arguments that we passed to it. What turns $LANG into the value of the LANG variable is the shell, Bash. Bash substitutes the text code $LANG by its value before passing the argument to echo.

Why are Multiple Spaces in a Variable's Value Not Printed When Using Echo?

In Bash, arguments are separated by any number of spaces, while echo merely joins the arguments it gets by a single space. Consequently, this happens:

> echo foo         bar
foo bar

Additionally, in Bash, a single variable may hold a list of arguments separated by spaces. Essentially, what happens is that Bash will just literally replace $FOO by its value as-is BEFORE parsing the command-line.

> FOO="foo         bar"
> echo $FOO
foo bar

Consequently, if a variable contains multiple spaces between words, the two mechanisms above will make echo print the variable's value wrong. Fortunately, there is a way to tell Bash that the value of a variable should be passed as a single argument: by surrounding it by double quotes.

> FOO="foo         bar"
> echo "$FOO"
foo         bar
Written by Noel Santos.

About the Author

I'm a self-taught Brazilian programmer graduated in IT from a FATEC. In a world of increasingly complex and essential computers, I decided to use my technical expertise in hardware, desktop applications, and web technologies to create an informative resource to make PC's easier to understand.

View Comments