配列にインデックスがあるかどうかをテストする方法

配列にインデックスがあるかどうかをテストする方法

私はプロジェクトフォルダをある場所から別の場所にコピーするGit Bashユーティリティを作成しています。ユーザーはプロジェクトを複数のターゲットにコピーしようとしますが、スクリプト実行ごとに1つの場所しか許可されません。これまでの論理はこうです。

#!/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

今まではそんなに良くなった。次に、ifユーザーが入力した値があるかどうかを確認するステートメントをtarget作成したいと思いますtargets。 PHPでは、array_key_exists($target, $targets)Bashの対応する値があります。

ベストアンサー1

以下を使用して、配列要素が空であるか空でないことを確認できます。

expr='^[0123456789]+$'
if [[ $target =~ $expr && -n "${targets[$target]}" ]]; then
    echo yes
else
    echo no
fi

また、応答が整数であることを確認する必要があります。これは、読み取りプロンプトでゼロと評価される文字列で応答して、配列の最初の要素を提供できるためです。

以下を使用することも検討できます。選ぶここで:

#!/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

おすすめ記事