【问题标题】:Bash: array iteration and check not returningBash:数组迭代并检查不返回
【发布时间】:2017-10-27 14:25:24
【问题描述】:

我想创建一个 bash 函数,它遍历数组并在数组中不存在作为参数传递的元素时返回 0,否则返回 1

但是,以下代码不会在 stdout 上打印任何内容。

function checkparsed {
  tocheck="$1"
  shift
  for item in $@
    do
      if [ "$item" = "$tocheck" ]; then
        return 0
      fi
  done
  return 1
}

mdfiles=('foo')
echo "$(checkparsed foo ${mdfiles[@]})"

【问题讨论】:

    标签: arrays bash function iteration


    【解决方案1】:

    您正在捕获函数的输出(没有)。

    要打印01,可以直接在函数中echo它们(别忘了return),或者在运行函数后使用echo $?

    要处理${mdfiles[@]} 中元素中的空格和全局字符,您应该使用双引号:

    for item in "$@"
    # and
    checkparsed foo "${mdfiles[@]}"
    

    【讨论】:

      【解决方案2】:

      这一行是问题:

      echo "$(checkparsed foo ${mdfiles[@]})"
      

      因为您的函数没有回显任何内容,但您正在返回值 01

      您实际上需要检查 $? 以获得函数的返回值:

      checkparsed foo ${mdfiles[@]}
      echo $?
      
      0
      

      或者在条件评估中使用返回值:

      checkparsed foo ${mdfiles[@]} && echo "found" || echo "not found"
      found
      
      checkparsed food ${mdfiles[@]} && echo "found" || echo "not found"
      not found
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-23
        • 2021-12-23
        • 2019-02-12
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多