如何测试数组中是否存在索引

kno*_*t22 6 bash array

我正在编写一个 Git Bash 实用程序,它将项目文件夹从一个位置复制到另一个位置。用户可能希望将项目复制到多个目标,但每次执行脚本只允许一个位置。到目前为止的逻辑是这样的 -

#!/bin/bash

# declare and initialize variables
source="/z/files/development/xampp/code/htdocs/Project7"

targets[0]="/z/files/development/xampp/code/htdocs/test/$(date +'%Y_%m_%d')"
targets[1]="/c/users/knot22/desktop/temp_dev/$(date +'%Y_%m_%d')"

# display contents of variables to user
echo "source " $source
echo -e "\nchoice \t target location"

for i in "${!targets[@]}"; do
  echo -e "$i \t ${targets[$i]}" 
done

echo

# prompt user for a target
read -p "Enter target's number for this copy operation: " target
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好。接下来我想编写一个if语句来检查用户输入的值是否targettargets. 在 PHP 中它将是array_key_exists($target, $targets). Bash 中的等价物是什么?

jes*_*e_b 5

您可以使用以下命令检查数组元素是否不为空/空:

expr='^[0123456789]+$'
if [[ $target =~ $expr && -n "${targets[$target]}" ]]; then
    echo yes
else
    echo no
fi
Run Code Online (Sandbox Code Playgroud)

您还必须检查响应是否为整数,因为人们可以使用字符串回复读取提示,该字符串的计算结果为零,从而为您提供数组中的第一个元素。

您可能还想考虑在此处使用select

#!/bin/bash

# declare and initialize variables
source="/z/files/development/xampp/code/htdocs/Project7"

targets[0]="/z/files/development/xampp/code/htdocs/test/$(date +'%Y_%m_%d')"
targets[1]="/c/users/knot22/desktop/temp_dev/$(date +'%Y_%m_%d')"

select i in "${targets[@]}" exit; do
    [[ $i == exit ]] && break
    echo "$i which is number $REPLY"
done
Run Code Online (Sandbox Code Playgroud)

  • @knot22:但是您是否还需要索引值,因为所选的数组元素将由 select 语句中的“$i”表示。所以你可以只执行 `cp "$i" ...` 而不必再次引用数组。 (2认同)