bash:检查字符串是否以“/*”开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37072671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:36:10  来源:igfitidea点击:

bash: check if string starts with "/*"

bashshell

提问by much

In a bash-script I need to check if the string $HEADERstarts with the character sequence "/*". I was trying:

在 bash 脚本中,我需要检查字符串是否$HEADER以字符序列“/*”开头。我在尝试:

if [ $(echo $HEADER | cut -c 1-2) = '/*' ]

It's not working as expected. It seems that the string is compared to the file list of the root directory.

它没有按预期工作。似乎将字符串与根目录的文件列表进行了比较。

How can I protect the characters / and * to be interpreted from the shell?

如何保护字符 / 和 * 以从 shell 解释?

To protect the characters with a backslash isn't working either.

用反斜杠保护字符也不起作用。

回答by Jahid

This should work:

这应该有效:

if [[ $HEADER = '/*'* ]]

Another solution would be:

另一种解决方案是:

if [ "${HEADER:0:2}" = '/*' ]

Or

或者

if [[ "${HEADER:0:2}" = '/*' ]]

回答by chepner

The problem is that the result of the command substitution is subject to file name generation. You need to quote that, as well as the expansion of $HEADERin the command substitution.

问题是命令替换的结果受文件名生成的影响。您需要引用that以及$HEADER命令替换中的 扩展。

if [ "$(echo "$HEADER" | cut -c 1-2)" = '/*' ]

Since you are using bash, using the [[command (which can perform pattern matching) is a superior solution though, as Jahid has already answered.

由于您正在使用bash,因此使用该[[命令(可以执行模式匹配)是一个很好的解决方案,因为 Jahid 已经回答了

if [[ $HEADER = '/*'* ]]

回答by dhke

You already have a few solutions, but

您已经有一些解决方案,但是

[ "${HEADER#/\*}" != "${HEADER}" ]

works with POSIX shellswithout using external tools (not counting [) or bashisms.

作品有POSIX壳,而无需使用外部工具(不包括[)或bash化。

Interestingly enough, this approach was missing from the marked duplicate.

有趣的是,标记的重复项中缺少这种方法。

回答by GMichael

This should help

这应该有帮助

if [[ $(echo $HEADER | grep -E '^\/\*' | wc -l) -gt 0 ]]