Bash shell provides environment and shell variables in order to hold data. These variables helps system administrators during the operations by giving clues and helpers. echo
command is used to put these variables to the standard output but in some cases some characters may misinterpreted and not work. In this tutorial we will look how to print bash variables accordingly with echo
command.
Echo Problem
The problem is that when we provide the variable and the variables have special characters like line feeds, asterisk, square brackets, it misbehaves like below.
$ test="This is *"
and than print with echo
$ echo $test

Echo Bash Variables
The most popular use case for echo
command is printing bash variables. We can use " "
double quotes where special characters will printed accordingly too.
$ myvar="This will printed accordingly" $ echo "$myvar"

Echo Environment Variable
We can also use this for shell variables. In this example we will print SSH_CLIENT
variable.
$ echo "$SSH_CLIENT"

Echo Tabs
While setting variables value we can use tabs
and spaces
. We if we try to echo this variable we will loose tabs
and spaces
. In order to prevent this we can use double quotes like below.
$ var=" title | count" $ echo "$var"

Echo Asterisks
Asterisk is meaningful operator for Linux bash. If we are using asterisks in our variables this may create misbehavior. In order to prevent this we should use double quotes like below.
$ var="This is *" $ echo "$var"

As we can see from examples *
will list current working directories if we do not use double quotes.