“echo -e” when called directly and when called via

2019-07-23 08:59发布

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?

标签: shell echo
1条回答
做自己的国王
2楼-- · 2019-07-23 09:21

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 and bash 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. (Though echo doesn't act like it has -e turned on by default in Bash's sh mode, so you're probably on a system whose sh is really dash.)

If you type sh at your prompt, you'll find that echo behaves the same way as in your script. But sh 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 putting bash 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.

查看更多
登录 后发表回答