如何检查鱼中是否存在数组?

How do I check if an array exists in fish?

我目前使用的方法似乎在这种特殊情况下工作正常,但当我第一次四处寻找答案时,我找不到任何与此相关的问题。因此,我当前如何检查数组的示例:

# An example array, $array_1, with three items.
set -l array_1 "item_1" "item_2" "item_3"
# How I'm checking if an array exists.
if test -n "$array_1"
  echo "The array exists."
end
# How I'm checking if an array doesn't exist.
if test -z "$array_2"
  echo "The array does not exist."
end
# How I'm checking if an array element exists.
if test -n "$array_1[2]"
  echo "Item 2 from the array_1 exists."
end

我不知道这是否是检查数组的建议方法,但目前这些方法适用于我的特定情况。在任何情况下这些方法都会失效吗?而且,有谁知道实现这些被认为是最佳实践的更好方法吗?

感谢任何和所有输入。希望这个问题的答案能帮助将来研究在鱼中使用数组的其他人 shell。

使用set -q.

if set -q array_1
    echo "array_1 exists"
end

if set -q array_1[2]
    echo "Item 2 from array_1 exists
end