tony19
tony19

Reputation: 138196

print carriage return in OSX bash

Why does echo-ing a carriage return from OSX Terminal behave differently than from a bash script?

From Terminal in OSX 10.7.3:

$ echo $SHELL
/bin/bash

$ /bin/bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11)
Copyright (C) 2007 Free Software Foundation, Inc.

$ echo -ne "hello\rbye"
byelo

But I see a different result from test.sh:

#!/bin/bash
echo -ne "hello\rbye"

...running test.sh gives me:

$ ./test.sh
byehello

I was expecting byelo. Why is it different? and how do I correct this?

Upvotes: 3

Views: 9615

Answers (2)

tony19
tony19

Reputation: 138196

It had something to do with #!/bin/sh at the top of my script. After I changed it to #!/bin/bash, I saw the expected output.

Upvotes: 2

David W.
David W.

Reputation: 107030

I just ran the same thing on my Mac, and got the same results.

I'm thinking two possibilities:

  • One of your set -o or shoot settings might be doing this
  • Your .bashrc (which would be called when you run a shell script) is doing something.

My results look like this:

$ echo -ne "hello\rbye"
bye$
$ test.sh   #Shell script with the one line in it
buy$ []

The [] represents the cursor. I have $PS1="$ ".

A suggesting, use printf if you want to do things like this.

$ printf "hello\rbye"

printf doesn't automatically add a CR line, and you don't have to give it any special options.

Upvotes: 2

Related Questions