Bash: echo string that starts with “-”

2019-03-18 00:51发布

VAR="-e xyz"
echo $VAR

This prints "xyz", for some reason. I don't seem to be able to find a way to get a string to start with -e.

What is going on here?

4条回答
手持菜刀,她持情操
2楼-- · 2019-03-18 01:23

The answers that say to put $VAR in quotes are only correct by side effect. That is, when put in quotes, echo(1) receives a single argument of -e xyz, and since that is not a valid option string, echo just prints it out. It is a side effect as echo could just as easily print an error regarding malformed options. Most programs will do this, but it seems GNU echo (from coreutils) and the version built into bash simply echo strings that start with a hyphen but are not valid argument strings. This behaviour is not documented so it should not be relied upon.

Further, if $VAR contains a valid echo option argument, then quoting $VAR will not help:

$ VAR="-e"
$ echo "$VAR"

$

Most GNU programs take -- as an argument to mean no more option processing — all the arguments after -- are to be processed as non-option arguments. bash echo does not support this so you cannot use it. Even if it did, it would not be portable. echo has other portability issues (-n vs \c, no -e).

The correct and portable solution is to use printf(1).

printf "%s\n" "$VAR"
查看更多
We Are One
3楼-- · 2019-03-18 01:25

The -e is being interpreted by bash as an argument to echo. Try

echo "$VAR"
查看更多
一夜七次
4楼-- · 2019-03-18 01:27

Try:

echo "$VAR"

instead.

(-e is a valid option for echo - this is what causes this phenomenon).

查看更多
该账号已被封号
5楼-- · 2019-03-18 01:39

The variable VAR contains -e xyz, if you access the variable via $ the -e is interpreted as a command-line option for echo. Note that the content of $VAR is not wrapped into "" automatically.

Use echo "$VAR" to fix your problem.

查看更多
登录 后发表回答