Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am writing a bash script, and I want to echo a string, but without a newline automatically added to the end. Reading the man page it says the flag is -n.

The problem is, when I do:

echo -n "My string is here"

The output in the bash script is:

-n My string is here

Any idea why the -n flag is being outputted instead of processed.

share|improve this question
    
Which distro are you using? –  quanta Sep 20 '11 at 9:05
    
:) LOL, on CentOS it works, but on OSx it does not. We are fine though, since its going to run on CentOS. –  Justin Sep 20 '11 at 9:09
2  
Please post this as an answer and accept it when you can –  Iain Sep 20 '11 at 9:11
add comment

3 Answers

up vote 5 down vote accepted

Check the shell you are using with:

echo $0

If it is /bin/sh, change to /bin/bash with chsh and try again.

http://hints.macworld.com/article.php?story=20071106192548833

share|improve this answer
    
This'll change your interactive shell, but the shell used for scripts is determined by the shebang line at the beginning of the script (e.g. #!/bin/sh). –  Gordon Davisson Sep 20 '11 at 18:08
add comment

echo is weirdly inconsistent between versions -- different versions of /bin/echo, as well as the builtin versions in various shells (even different versions of the same shell). Some versions understand options (like -n), some versions understand escape sequences within the string (end with "\c" to skip the newline). Some versions use a weird mix of the two.

If you want consistent behavior, avoid echo and use printf instead. It's a little more complicated, but it's much more predictable:

printf "%s" "My string is here"
share|improve this answer
add comment

Works on CentOS, but appears that OSX does not like the -n flag.

share|improve this answer
    
That's weird. I have several scripts on OS X Lion and Snow Leopard that use echo -n successfully. –  slillibri Sep 20 '11 at 9:19
1  
It depends on which shell is running the script, usually dictated by the #! on the first line. If you explicitly ask for bash (#!/bin/bash) or some other shell that definitely supports the option then echo -n. On some systems the shell that /bin/sh represents is Bash or similar, but it could be something very simple that only implements the minimum functionality required to be POSIX compliant (and this doesn't include the -n option for echo). –  David Spillett Sep 20 '11 at 11:10
    
It also depends on the version of OS X (and hence bash) -- 10.4 understands -n just fine, but 10.5.0 doesn't. –  Gordon Davisson Sep 20 '11 at 18:10
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.