1

When I run the following command from the terminal:

echo -n hello >> output.txt

It appends 'hello' to the file and doesn't add a trailing newline, which is what I want it to do.

However, if I have a file named prog.sh with that exact same line as its sole contents, and run it from terminal with

sh prog.sh

then it appends '-n hello' to the file with a trailing newline.

I have run scripts using this before, and it has never been a problem. What am I missing?

Henry Brice
  • 280
  • 1
  • 2
  • 18
  • 3
    `sh` is not `bash` (or more precisely, `bash` when invoked as `sh` behaves differently). POSIX doesn't require that `-n` be treated as an option; it only *allows* for it to be an option. – chepner Sep 27 '17 at 12:12
  • @chepner `sh prog.sh` works for me - it does write "hello" without new line. What makes the difference? – Maroun Sep 27 '17 at 12:13
  • That's interesting, however I've used exactly that wording (obviously on more complex scripts) hundreds of times before, and it's never been a problem. Running it with `bash prog.sh` does work properly, but I can't work out why it has always worked in the past, but doesn't work now. What could have changed? – Henry Brice Sep 27 '17 at 12:17
  • 2
    @HenryBrice Computers do not obey us anymore. Within few years you'll run bash script for them. – Maroun Sep 27 '17 at 12:19
  • Henry, try 1) `/bin/sh echo -n hello`, 2) switching `#!/bin/sh` to `#!/bin/bash` in the script and running it again, and 3) doing `which sh` to make sure `sh` and `/bin/sh` are the same program. The results from those should definitively tell us whether chepner's right about your `sh` not supporting `echo -n`. – Ray Sep 27 '17 at 12:25
  • 2
    The right thing to do is stop using `echo`, and use `printf` instead: `printf '%s' hello`. – chepner Sep 27 '17 at 12:26
  • 1
    @MarounMaroun When invoked as `sh`, `bash` 3.2 treats `-n` as a regular argument to print. Starting with `bash` 4, it treats it as an option to supress a newline. All the more reason to stop using `echo` if you expect consistent results. – chepner Sep 27 '17 at 12:28
  • 1
    @chepner How do you know that `printf` will be interpreted the same? (In general, how can I know if a command I use is the same in all tools?). – Maroun Sep 27 '17 at 12:33
  • @chepner if you add an answer, I'll accept it. Thanks! – Henry Brice Sep 27 '17 at 12:34
  • 2
    The POSIX standard simply threw up its hands and allowed `echo`'s behavior to be implementation-defined to accommodate the variety of historical implementations. `printf` was much more consistent to begin with, and so is much more strictly defined. – chepner Sep 27 '17 at 12:35
  • 2
    @MarounMaroun A good write up on printf vs echo can be found at https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo – Eric Renouf Sep 27 '17 at 12:43
  • @MarounMaroun hahaha... you made me lol. – Matias Barrios Sep 27 '17 at 16:59

0 Answers0