2017-07-15 10 views
0

私は、入力日付($ 1)が範囲/日付の範囲に入るかどうかをチェックするbashスクリプトを持っています。ユーザーは日付と(aまたはb、$ 2です)を入力します。連想配列名置換とコピーbash

#!/usr/bin/env bash 

today=$(date +"%Y%M%d") 
declare -A dict=$2_range 
a_range=(["20140602"]="20151222" ["20170201"]="$today") 
b_range=(["20140602"]="20150130") 

for key in ${!dict[@]}; do 
    if [[ $1 -le ${dict[$key]} ]] && [[ $1 -ge $key ]]; then 
    echo $1 falls in the range of $2 
    fi 
done 

私はdictの変数に連想配列をコピーする方法がわかりません。あなたがすべてで何かをコピーする必要はありません 使用例

$ ./script.sh 20170707 a 

    20170707 falls in the range of a 
+0

「b_range」は範囲ではありません。 – Jack

+0

私は、キーと値のペアとして開始日と終了日を持っています。その範囲ではありません – pdna

+0

なぜ 'a_range 'に2つの要素がありますか? – Jack

答えて

2

。エイリアスが必要です。

#!/usr/bin/env bash 

today=$(date +"%Y%M%d") 

# you need declare -A **before** data is given. 
# previously, these were sparse indexed arrays, not associative arrays at all. 
declare -A a_range=(["20140602"]="20151222" ["20170201"]="$today") 
declare -A b_range=(["20140602"]="20150130") 

# declare -n makes dict a reference to (not a copy of) your named range. 
declare -n dict="$2_range" 

for key in "${!dict[@]}"; do 
    if (($1 <= ${dict[$key]})) && (($1 >= key)); then 
    echo "$1 falls in the range of $2" 
    fi 
done 

declare -nでは、ksh93機能namerefのバッシュ(4.3以上)バージョンです。 http://wiki.bash-hackers.org/commands/builtin/declare#nameref

+0

ああ、私は$ 2_rangeの周りの引用符を逃した。私はこれまでdict = $ 2_rangeを試してみました。ありがとう – pdna

+0

これらの引用符は厳密に必須ではありません。違いを生むのは「宣言-n」です。 –

+0

私は前に 'declare -n'と上記の変更を試みました。たぶん私は変更の間違った組み合わせを試みた。説明をありがとう – pdna