在这里查看一些类似的问题,但仍然卡住了。我的代码有什么问题?
check_conf_result=$(apachectl configtest 2>&1)
echo "Result of checking apache config: $check_conf_result"
if [[ "$check_conf_result" == *"Syntax OK"* ]]; then
echo "Reload apache config"
invoke-rc.d apache2 reload
else
echo "Apache configure files wrong."
#exit 1
fi
输出是:
Result of checking apache config: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Syntax OK
/var/lib/dpkg/info/mybash.postinst: 114: [: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Syntax OK: unexpected operator
Apache configure files wrong.
谢谢。
更新
下面的一段代码有效。 但是还是很奇怪为什么上面这段代码不行??? (顺便说一下,这是 debian/mybash.postinst 的一部分)。通过搜索“[[: not found”,我发现如果我使用“if [[ "$check_conf_result"== "Syntax OK" ]] 我应该使用“#!/bin/bash” ; 然后”。最后,我在下面使用了 case 语句。
case "$check_conf_result" in
*Syntax[[:space:]]OK*)
echo "Reload apache config"
invoke-rc.d apache2 reload
;;
*)
echo "Apache config files wrong."
exit 1
;;
esac
最佳答案
在 bash 中,单个方括号不执行模式匹配。为了使用它,你必须使用双方括号:
if [[ "$check_conf_result" == *"Syntax OK"* ]] ; then
这在 man bash
中有记录:
string1 == string2 string1 = string2
True if the strings are equal.
=
should be used with the test command for POSIX conformance. When used with the[[
command, this performs pattern matching as described above (Compound Commands).
测试:
#!/bin/bash
check_conf_result="Result of checking apache config: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Syntax OK"
if [[ "$check_conf_result" == *"Syntax OK"* ]] ; then
echo Matches.
fi
关于bash - 如何检查bash中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419218/