Marco
Marco

Reputation: 1232

linux echo/print removing 1 space in string when printing multiple variables

When I try to echo or print a string, it prints fine.

This is the string.

IP_NET_TP0                                                                               _

The structure is IP_NET_TP0, and 9 tabs (\t), then 7 spaces and 1 underscore at the end.

Ok, if you put that into a variable, let's say var1 and you print it as follows it works great.

echo $var1 
echo "$var1"

BUT, if you add extra texts to it, for example, adding quotes, or adding a letter, it removes 1 space from the chain.

echo \"$var1\" 
echo "'"$var1"'"
echo "a" $var1

WHY?! .. I have tried printing the variable with print, or like this ${var1}, and the output if the same, with 1 space less.

The following shows, the first one when printed with something else, and the second when printed alone.

IP_NET_TP0                                                                             _
IP_NET_TP0                                                                               _

Any help will be great.

Upvotes: 1

Views: 767

Answers (3)

Marco
Marco

Reputation: 1232

Issue fixed, as the string was built converting spaces to tabs, there are tabs with different sizes! ... causing probably an interpretation issue when printed, what I did was, before printing the variable, convert all the tabs to spaces so the size won't change any more like this var2=echo $var1 | expand` ... and done, the size is now fixed and it is not going to change any more.

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

you didn't write the echo correctly when adding the extra patterne

echo \"$var1\" -> echo "\"$var1\""
echo "'"$var1"'" -> echo "'$var1'"
echo "a" $var1 -> echo "a $var1"  #if space is needed between a and the var1

also try to use ${var1} to avoid confusion when like this

var="1 x 1 = "
var1="Something"
echo "$var1"
echo "${var}1"
echo "${var1}"

Upvotes: 1

Luke Mat
Luke Mat

Reputation: 157

Perhaps you are instantiating the variable incorrectly. When I declare it like this var1="IP_NET_TP0" or var1=IP_NET_TP0 printing it the ways you did works fine. Are you using bash or a different type of shell? There might also be something weird in your .bash_profile or .bashrc causing this.

Upvotes: 3

Related Questions