【发布时间】:2020-08-23 03:28:57
【问题描述】:
如何在 bash shell 的第一个位置检查字符串中的子字符串 0? 在下面的代码中,它说命令是错误的。
#!/bin/bash
Stdalt=$(date +"%H")
if ["${Stdalt:0:1}" -eq "0"]
then
...
fi
【问题讨论】:
-
总是先咨询shellcheck.net。
如何在 bash shell 的第一个位置检查字符串中的子字符串 0? 在下面的代码中,它说命令是错误的。
#!/bin/bash
Stdalt=$(date +"%H")
if ["${Stdalt:0:1}" -eq "0"]
then
...
fi
【问题讨论】:
== 比较运算符在双括号中的行为不同
[[ $Stdalt == 0* ]] # True if $Stdalt starts with Stdalt "0" (wildcard matching).
[[ $Stdalt == "0" ]] # True if $Stdalt is equal to 0* (literal matching).
这里是你要找的:
#!/bin/bash
Stdalt=$(date +"%H")
if [[ $Stdalt == 0* ]]
then
echo "Yes"
fi
另外,您可以只选择要检查的字符串部分:
if [[ "${Stdalt:0:1}" = "0" ]]
then
.
.
fi
【讨论】: