检查 Bash 中的子字符串时出错
Error when checking for substring in Bash
我对 shell 脚本编写还很陌生,在尝试检查字符串中的子字符串时遇到了问题。
我想构建代码来检查您是否 运行 正在使用基于 64 位的系统。这由第一行中 x86_64
的 uname -m && cat /etc/*release
命令的输出指示。
这是我的代码:
INFO=$(uname -m && cat /etc/*release)
if [ "$INFO" == *"x86_64"* ]
then
echo "You are running a 64bit-based system!"
else
echo "Your system architecture is wrong!"
exit
fi
虽然我 运行 一个基于 64 位的系统并且 x86_64 出现在我的命令的输出中,但 if 语句仍然 returns 错误,所以我得到了输出Your system architecture is wrong!
。应该是相反的。
有人可以通过确定我做错了什么来帮助我吗?我也接受改进我的方法的一般建议,但首先,我想知道错误在哪里。
非常感谢您的帮助!
对于 bash 版本 >= 3,您可以使用正则表达式:
[[ "$INFO" =~ x86_64 ]]
[
命令[
等同于test命令。 test
不支持任何类型的高级匹配。 test
可以将字符串与 =
进行比较 - 在 test
中将字符串与 ==
进行比较是一个 bash 扩展。
通过做:
[ "$INFO" == *"x86_64"* ]
你实际上是 运行 命令,如 [ "$INFO" == <the list of files that match
"x86_64"pattern> ]
- *"x86_64"*
进行文件名扩展.如果您有一个名为 something_x86_64_something
的文件,它将被放置在那里,与 cat *"x86_64"*
的工作方式相同。
bash 扩展 [[
command 支持模式匹配。做:
if [[ "$INFO" == *"x86_64"* ]]
对于始终适用于任何类型 posix shell 的可移植脚本,请使用 case
:
case "$INFO" in
*x86_64*) echo yes; ;;
*) echo no; ;;
esac
检查 64 位的一种方法是简单地 grep /bin/arch
的输出
if /bin/arch | grep -q x86_64
then
echo "it is 64 bit"
else
echo "it is not"
fi
不确定为什么会这样,但您的代码在加倍方括号后开始工作:
INFO=$(uname -m && cat /etc/*release)
if [[ "$INFO" = *x86_64* ]]
then
echo "You are running a 64bit-based system!"
else
echo "Your system architecture is wrong!"
exit
fi
也许可以在 Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash? 等下找到一些解释。
我对 shell 脚本编写还很陌生,在尝试检查字符串中的子字符串时遇到了问题。
我想构建代码来检查您是否 运行 正在使用基于 64 位的系统。这由第一行中 x86_64
的 uname -m && cat /etc/*release
命令的输出指示。
这是我的代码:
INFO=$(uname -m && cat /etc/*release)
if [ "$INFO" == *"x86_64"* ]
then
echo "You are running a 64bit-based system!"
else
echo "Your system architecture is wrong!"
exit
fi
虽然我 运行 一个基于 64 位的系统并且 x86_64 出现在我的命令的输出中,但 if 语句仍然 returns 错误,所以我得到了输出Your system architecture is wrong!
。应该是相反的。
有人可以通过确定我做错了什么来帮助我吗?我也接受改进我的方法的一般建议,但首先,我想知道错误在哪里。
非常感谢您的帮助!
对于 bash 版本 >= 3,您可以使用正则表达式:
[[ "$INFO" =~ x86_64 ]]
[
命令[
等同于test命令。 test
不支持任何类型的高级匹配。 test
可以将字符串与 =
进行比较 - 在 test
中将字符串与 ==
进行比较是一个 bash 扩展。
通过做:
[ "$INFO" == *"x86_64"* ]
你实际上是 运行 命令,如 [ "$INFO" == <the list of files that match
"x86_64"pattern> ]
- *"x86_64"*
进行文件名扩展.如果您有一个名为 something_x86_64_something
的文件,它将被放置在那里,与 cat *"x86_64"*
的工作方式相同。
bash 扩展 [[
command 支持模式匹配。做:
if [[ "$INFO" == *"x86_64"* ]]
对于始终适用于任何类型 posix shell 的可移植脚本,请使用 case
:
case "$INFO" in
*x86_64*) echo yes; ;;
*) echo no; ;;
esac
检查 64 位的一种方法是简单地 grep /bin/arch
的输出if /bin/arch | grep -q x86_64
then
echo "it is 64 bit"
else
echo "it is not"
fi
不确定为什么会这样,但您的代码在加倍方括号后开始工作:
INFO=$(uname -m && cat /etc/*release)
if [[ "$INFO" = *x86_64* ]]
then
echo "You are running a 64bit-based system!"
else
echo "Your system architecture is wrong!"
exit
fi
也许可以在 Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash? 等下找到一些解释。