简体   繁体   中英

Echo is not printing certain variables

I'm having some problem with my code not printing certain variables even if the variables has a string in it.

$ dmisysname=$(sed -ne 148p ./3A47083/S09850724414683/002590F3851A.txt | awk -F '=' '{ print $2 }' | sed 's/ //')
$ dmibrdname=$(sed -ne 157p ./3A47083/S09850724414683/002590F3851A.txt | awk -F '=' '{ print $2 }' | sed 's/ //')
$ echo $dmisysname $dmibrdname

This should give me whatever inside $dmisysname and $dmibrdname, but the output displays this:

X9DRi-LN4+/X9DR3-LN4+

To make sure that the 2 variables have a string in it, I echo each variable individually.

$ echo $dmisysname

PIO-647R-6RLN4F+-ST031

$ echo $dmibrdname

X9DRi-LN4+/X9DR3-LN4+

Am I doing something wrong that has to do something with the print buffer or is there a bigger problem that I don't see?

Your input file was created under windows, and as such uses CRLF line terminations. This causes the output from under to be confused, relative to what is expected, as per @Lurker's useful explanation .

Use the dos2unix utility to fix your file:

$ dmisysname=$(sed -ne 148p ./3A47083/S09850724414683/002590F3851A.txt | awk -F '=' '{ print $2 }' | sed 's/ //')
$ dmibrdname=$(sed -ne 157p ./3A47083/S09850724414683/002590F3851A.txt | awk -F '=' '{ print $2 }' | sed 's/ //')
$ echo $dmisysname $dmibrdname
 X9DRi-LN4+/X9DR3-LN4+
$ dos2unix 3A47083/S09850724414683/002590F3851A.txtdos2unix: converting file 3A47083/S09850724414683/002590F3851A.txt to Unix format ...
$ dmisysname=$(sed -ne 148p ./3A47083/S09850724414683/002590F3851A.txt | awk -F '=' '{ print $2 }' | sed 's/ //')
$ dmibrdname=$(sed -ne 157p ./3A47083/S09850724414683/002590F3851A.txt | awk -F '=' '{ print $2 }' | sed 's/ //')
$ echo $dmisysname $dmibrdname
PIO-647R-6RLN4F+-ST031 X9DRi-LN4+/X9DR3-LN4+
$ 

I recreated a workable version of your file under Linux, then used unix2dos to format it as per windows. Then I am able to recreate your problem. Reverting it back using dos2unix fixes it.

Each of your variables ends in a carriage return ( \\r ). So what happens is both are echoed, but the second one overwrites the first.

I'll illustrate with the -e option:

$ echo -e "FOO\rBAR\r"
BAR

But both are being echoed. It's just that BAR is overwriting FOO :

$ echo -e "FOO\rBAR\r" | od -c
0000000   F   O   O  \r   B   A   R  \r  \n
0000011

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM