Space truncation

HI All-

We have script like the following

a='h1    '
b='12434    '
c='   fagkasdbkZ<M'

output=$a$b$c
echo $output > /home/dsomasun/fil_concat.txt

But in the output file spaces are truncated and Output is coming like the below

h1 1234 fagkasdbkZ<M

please advise

Hello dhilipans1988,

Welcome to forum, kindly use code tags for commands/inputs/codes which you are using in your posts as per forum rules. You should use printf for same because it is known behavior for echo .

singh_test@Singh$ a='h1 '
singh_test@Singh$ b='12434 '
singh_test@Singh$ c=' fagkasdbkZ<M'
singh_test@Singh$ printf "$a $b $c\n" > testpri
singh_test@Singh$ cat testpri
h1  12434   fagkasdbkZ<M
 

Hope this helps, enjoy learning and sharing knowledge in forum:b:

Thanks,
R. Singh

1 Like

The difference is in the quoting. The shell will strip out multiple spaces.

Use echo "$a$b$c" instead.

Better still, you should also use { & } around variable names to clearly mark where they start and end and printf instead of echo so you would end up with:-

printf "${a}${b}${c}"

Unfortunately, echo can vary between vendors.

Robin

1 Like

Thank you All.. It worked!!!!

The echo is dangerous if any if the first variable expands to a string starting with a hyphen or if any of the variables expand to a string containing any backslash characters. Otherwise:

echo "$a$b$c"

is fine. But, if you're reading data from a user supplied source, never assume that you know what the data will contain, and, as Robin suggested, use printf instead.

But:

printf "${a}${b}${c}"

is also dangerous (and doesn't add the trailing <newline> character that echo would provide). The dangers are the same as with echo but has an additional problem if the expansion of any of those variables contain a <percent-sign> character. The safe way to print three variables (with no added space between them and with a trailing <newline>) would be:

printf '%s%s%s\n' "$a" "$b" "$c"

You only need to include braces around variable names if text following the variable name could be part of a valid variable name. For instance if you wanted to print the expansion of the variable b followed by the character b you could use either of the following:

printf '%sb\n' "$b"
printf '%s\n' "${b}b"

but not either of:

echo "$bb"
printf '%s\n' "$bb"

since both of those you result in the expansion of the variable bb instead of the variable b . Shell variable names can contain letters, digits, and underscores where the 1st character is not a digit.

Positional parameters look like variable names just containing digits, but the rules are slightly different. Single digit positional parameters never require (but do allow) braces but multi-digit positional parameters always require braces. The expansion of $11 (or of ${1}1 ) will result in the expansion of the 1st positional parameter followed by the digit 1. To get the expansion of the 11th positional parameter, you must use ${11} .

1 Like