以下失败,我不明白为什么:
$ echo "#!"
以下也失败并显示相同的错误消息:
$ echo "\#!"
错误信息:
-bash: !": event not found
为什么会失败? echo
应该如何代替?
最佳答案
!
字符用于csh
样式的历史扩展。
如果您不使用此功能,set +o histexpand
(又名 set +H
)将关闭此行为。它对于脚本是关闭的,但通常为交互式使用而启用。在这种情况下,我个人的建议是通过将 set +o histexpand
添加到您的 .bash_profile
(或 .bashrc
如果您没有 .bash_profile
;这比我想放入括号中要复杂得多。
作为解决方法,如果出于某种原因您不能或不想关闭并忘记此遗留 csh
功能,您可以使用单引号而不是双引号 - 请记住,当然,它们的语义不同。例如,如果您需要将引用与变量插值相结合,您可以更改
echo "#!$SHELL" # oops, history expansion breaks this
进入
echo '#!'"$SHELL"
(注意相邻的单引号和双引号字符串;在 shell 完成此操作后,引号将被删除,字符串 #!
将在值的旁边输出变量 SHELL
之间没有空格)或许多其他常见的解决方法,如
printf '#!%s\n' "$SHELL"
...尽管如评论中所述,即使是single quotes don't necessarily prevent this from happening when they are at the end of a pipeline.
关于bash - echo "#!"失败 -- "event not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48237424/