Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables overwriting text problem with "echo" in Bash

Tags:

bash

echo

macos

I use OS X 10.6.5, Bash.

When I run this:

echo $IP; echo of; echo $IPLINES

I get this output:

219.80.4.150:3128
of
1108

When I run this:

echo $IP of $IPLINES

I get this output:

 of 1108.150:3128

I expected to get:

219.80.4.150:3128 of 1108

What would cause the distorted output I am getting?

The actual script is this:

#!/bin/bash

IPLINES=`cat a.txt | wc -l | awk '{print $1}'`

if [ $IPLINES > 1 ]; then
    LINE=`expr $RANDOM % $IPLINES + 1`
    IP=`head -$LINE a.txt | tail -1`
    sed -e "${LINE}d" -i .b a.txt

    echo $IP of $IPLINES
fi
like image 877
zevlag Avatar asked Dec 10 '10 18:12

zevlag


People also ask

How do I stop bash from overwriting?

How do I avoid accidental overwriting of a file on bash shell? You can tell bash shell not to delete file data / contents by mistake by setting noclobber variable. It can keep you from accidentally destroying your existing files by redirecting input over an already-existing file.

Does echo work in bash?

The echo command is one of the most commonly and widely used built-in commands for Linux bash and C shells, that typically used in a scripting language and batch files to display a line of text/string on standard output or a file.


2 Answers

A wild guess here: you are extracting the IP variable from a .txt file -- if that's a Windows file, or is encoded Windows-style, lines end with \r\n. You take the newline away, but what if there's a \r in it that's making you go back to the beginning of the line?

Quick dirty fix with no questions asked: use echo -n, it supresses the newline at the end of the echoed text.

echo -n $IP; echo -n of; echo -n $IPLINES

If the problem persists, it's probably what I said above. Try right-trimming $IP.

EDIT: didn't see the OSX part, sorry. In OSX, lines end with \r -- that must be the issue.

like image 155
slezica Avatar answered Nov 15 '22 01:11

slezica


It would appear that there is a carriage return (\r) at the end of $IP.

like image 26
Andrew Clark Avatar answered Nov 15 '22 01:11

Andrew Clark