Arrays Bash:数组迭代和检查不返回

Arrays Bash:数组迭代和检查不返回,arrays,bash,function,iteration,Arrays,Bash,Function,Iteration,我想创建一个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') ech

我想创建一个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[@]})"

这一行就是问题所在:

echo "$(checkparsed foo ${mdfiles[@]})"
因为函数没有回显任何内容,而是返回值
0
1

实际上,您需要检查函数返回值的
$?

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

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

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

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

这一行就是问题所在:

echo "$(checkparsed foo ${mdfiles[@]})"
因为函数没有回显任何内容,而是返回值
0
1

实际上,您需要检查函数返回值的
$?

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

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

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

checkparsed food ${mdfiles[@]} && echo "found" || echo "not found"
not found
您正在捕获函数的输出(没有)

要打印
0
1
,请直接在函数中使用
echo
(不要忘记
return
),或在运行函数后使用
echo$?

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

for item in "$@"
# and
checkparsed foo "${mdfiles[@]}"
您正在捕获函数的输出(没有)

要打印
0
1
,请直接在函数中使用
echo
(不要忘记
return
),或在运行函数后使用
echo$?

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

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