【问题标题】:Check for installation of xCode always returns true检查 xCode 的安装总是返回 true
【发布时间】:2015-05-06 21:31:25
【问题描述】:

我正在尝试检查 xCode 的安装。这个:

function xCodeCheck(){
    if xcode-select -p; then
        return 1
    else
        return 0
    fi
}
if xCodeCheck -eq 1; then
    echo "it's here"
else
    echo "it's not here"
fi

尽管总是返回 true。不管是否安装了程序。如果不存在,如何使false返回?

【问题讨论】:

  • 空格很重要 if 语句它测试将 =true 分配到 xCodeCheck 变量是否成功(在此之后运行 echo "$xCodeCheck" 以了解我的意思)。 Shell 函数不能仅返回数字值的字符串。要测试字符串,您需要使用[/test。通过shellcheck.net 运行您的代码,直到它返回没有错误。
  • @EtanReisner 我纠正了几个错误,但仍然在第 8 行得到SC2034 xCodeCheck appears unused. Verify it or export it.。我不知道那是什么意思。
  • 这是分配问题。 if xCodeCheck==true; then 是测试中的变量赋值。与if res=$(some-command-that-might-fail); then 相同。所以 shellcheck 告诉你你没有在任何地方使用 xCodeCheck 变量,所以赋值突出为“奇数”。你只想在这里if xcode-select -p; then。你不需要这个包装函数。
  • @EtanReisner double equal 是 bash 中的赋值吗?
  • @EtanReisner 你能看到我最近的更新吗?这样更好吗?

标签: linux bash


【解决方案1】:

您的代码的工作版本是这样的:

function xCodeCheck(){
    if xcode-select -p; then
        return 0
    else
        return 1
    fi
}
if xCodeCheck; then
    echo "it's here"
else
    echo "it's not here"
fi

请注意,我反转了 0/1 返回值,因为 shell 中 0 的退出/返回状态是 true,其他所有状态都是 false

话虽如此,整个包装功能毫无意义。

你可以很容易地写:

xCodeCheck() {
    xcode-select -p
}

并让xCodeCheck 直接返回xcode-select 的返回值,而不是在if 中捕获它并将其规范化为01

话虽如此,您可以在第一个测试中使用xcode-select -p

if xcode-select -p; then
    echo "it's here"
else
    echo "it's not here"
fi

如果您想保留手动返回和手动值检查,您的原始代码需要编写为:

function xCodeCheck(){
    if xcode-select -p; then
        return 1
    else
        return 0
    fi
}

if xCodeCheck; [ $? -eq 1 ]; then
    echo "it's here"
else
    echo "it's not here"
fi

【讨论】:

  • ... 或 if ! xCodeCheck; then ,这或多或少表明,将 1 返回为真是愚蠢的(在 shell 中)。
  • 感谢这些详细的解释。关于最后一个示例的一些后续操作:在您有两个分号的地方,语法是什么意思?(if xCodeCheck; [ $? -eq 1 ];)为什么第二个用方括号括起来? ([ $? -eq 1 ];)
  • if 语句的语法是if <command_list>; then。您可以在<command_list> 中添加任何内容。在最后一种情况下,命令列表是两个命令。调用xCodeCheck,然后调用[/test 内置函数。我对此进行了更多解释 herehere
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2013-08-06
相关资源
最近更新 更多