I've noticed echo
behaves slightly differently when called directly
root$echo "line1\nline2"
and when called via a script:
#! /bin/sh
echo "line1\nline2"
[...]
The first case would print:
line1\nline2
, while the latter would print
line1
line2
So echo
is always assumed to have flag -e
when used in a script?
Your script has a shebang line of
#! /bin/sh
, while your interactive shell is probably Bash. If you want Bash behavior, change the script to#! /bin/bash
instead.The two programs
sh
andbash
are different shells. Even on systems where/bin/sh
and/bin/bash
are the same program, it behaves differently depending on which command you use to invoke it. (Thoughecho
doesn't act like it has-e
turned on by default in Bash'ssh
mode, so you're probably on a system whosesh
is reallydash
.)If you type
sh
at your prompt, you'll find thatecho
behaves the same way as in your script. Butsh
is not a very friendly shell for interactive use.If you're trying to write maximally portable shell scripts, you should stick to vanilla
sh
syntax, but if you aren't writing for distribution far and wide, you can use Bash scripts - just make sure to tell the system that they are, in fact, Bash scripts, by puttingbash
in the shebang line.The
echo
command is probably the most notoriously inconsistent command across shells, by the way. So if you are going for portability, you're better off avoiding it entirely for anything other than straight up, no-options, no-escapes, always-a-newline output. One pretty portable option is printf.