我有一个bash脚本,用于检查输入日期($ 1)是否属于某个范围/日期范围。用户输入日期和(a或b,即$ 2)。
#!/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 :(得分: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
的bash(4.3+)版本;见http://wiki.bash-hackers.org/commands/builtin/declare#nameref