我假设真正的问题是为什么:
C#或Java函数永远不会根据你调用它的方式 foo(4)
或 foo(2+2)
或 foo((int)16/4)
而表现出不同的行为,因为这些信息在函数运行时就已经消失了。它可以知道你传递了什么,但无法知道你是如何传递的。
出于同样的原因,一个命令永远不会根据你如何转义其参数而表现出不同的行为。引号和转义是一种“how”,而结果字符串参数是“what”。
以下是每个尝试的等效 execlp
调用(echo
是 bash 内置的,但行为相同):
# v-- How you passed it v-- What you passed
echo -e # execlp("echo", "echo", "-e", 0); # prints nothing
echo '-e' # execlp("echo", "echo", "-e", 0); # prints nothing
echo "-e" # execlp("echo", "echo", "-e", 0); # prints nothing
echo \-e # execlp("echo", "echo", "-e", 0); # prints nothing
echo \\-e # execlp("echo", "echo", "\\-e", 0); # prints \-e
echo '\-e' # execlp("echo", "echo", "\\-e", 0); # prints \-e
echo "'-e'" # execlp("echo", "echo", "'-e'", 0); # prints '-e' (with quotes)
echo -- -e # execlp("echo", "echo", "--", "-e", 0); # prints -- -e
正如您所看到的,how并不会对输出产生任何影响。最终结果取决于what。这就是为什么无论进行多少转义,都无法达到预期效果的原因。
printf '%s\n' -e
?它不使用echo
,但会打印出您想要的结果。 - Jonathan Leffler