shellinitializationubuntu-9.04

Overlapped data when amend values of variables in shell script ubuntu 9.04 for ARM


I created a shell script in /etc/init.d/ to start/stop my application. The script is based on a skeleton script file which was originally located in /etc/init.d. This script imports variables from the xxx.conf configuration file.

# Read configuration variable file if it is present
[ -r /etc/xxx.conf ] && . /etc/xxx.conf

When assigning each imported variable and printing out the value with echo, it works well.

local A
A=$imported1
#print out exactly actual value of imported1
echo $A
local B
B=$imported2
#print out exactly actual value of imported1
echo $B
local C
C=$imported3
#print out exactly actual value of imported3
echo $C

However, when amending A, B, and C into a new string or even amending imported1, imported2, and imported3 into a new string, these values will overlap each other.

local D
D="$A $B $C"
#print out value is overlap string of A,B and C instead of 'A B C'
echo $D
D="$imported1 $imported2 $imported3" 
#print out value is overlap string of imported1 ,imported2  and 
#imported3,as same as result when do echo "$A $B $C"
echo $D 

How can I amend these imported variables correctly?


Solution

  • I suspect you might have some control characters hidden in your variables. Probably a carriage return, which moves the cursor to the start of the line when you print it to a terminal.

    You can make a carriage return many different ways -- this example will use echo -e "\r":

    A="$(echo -en 'A LONG WORD\r')"
    B="$(echo -en 'short\r')"
    

    Just like in your example, printing them individually will look like they only contain letters:

    $ echo $A
    A LONG WORD
    $ echo $B
    shorter
    

    But if you print them together, the later one overlaps the earlier one:

    $ echo "$A $B"
     short WORD
    

    You can see the carriage return if you look at the output with less, od -a, or anything that doesn't interpret that control character to move the cursor.