如果不使用通配符值

if not working with wildcard value

我有一个基本具有函数的脚本,然后如果内核版本是我需要的版本,我 运行 将 if 设置为 运行 函数。简而言之,脚本如下所示

#!/bin/bash

postinstall() {
run some postinstall commands in here
}

UNAME=`uname -r`
if [[ $UNAME == 3.* ]]
then
  postinstall
else
  echo "Kernel version is not correct"
fi

当我 运行 CLI 上的命令一切正常时,但是当我以 sh <scriptname> 触发脚本时,我得到以下结果:

: 313: <scriptname>.sh: [[: not found
Kernel version is not correct

第 313 行带有 "if"。

正如我在 中指出的那样,安装为 /bin/sh 的 shell 不一定是 Bash(例如,在 Ubuntu 上,它通常是 dash),即使它是 Bash,它在 运行 时的行为也不同于 sh 而不是 bash

然而,作为chepner pointed out in a , even when run as sh (in Bash's POSIX mode), Bash recognizes the [[ command — though it doesn't recognize some other extensions to POSIX shell syntax, such as process substitution.

鉴于您看到的错误消息,很明显在您的机器上,sh 无法将 [[ 识别为有效命令,这反过来意味着它可能不是 Bash.因此,你不应该 运行 它与 sh 而是 bash。或者 运行 它没有在命令行上指定 shell,让 shebang (#!/bin/bash) 确保内核 运行 是正确的 shell.