2017-07-15 53 views
0

我有一个bash脚本,用于检查输入日期($ 1)是否落入日期范围/范围内。用户输入日期和(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'中有两个元素? – 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是在bash(4.3+)的ksh93的特征nameref的版本;见http://wiki.bash-hackers.org/commands/builtin/declare#nameref

+0

啊,我错过了2美元左右的报价。到目前为止,我只尝试过dict = $ 2_range。谢谢 – pdna

+0

这些引号不是绝对必要的。这是'声明-n',这是有所作为的。 –

+0

我已经尝试过'声明-n'和上面的更改。也许我尝试了错误的组合变化。感谢您的解释 – pdna