I have a bash script which checks if the input date($1) falls in a range/ranges of dates. User inputs a date and (a or b, which is $2).
我有一个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
I do not know how to copy the associative array to the dict variable. Sample usage
我不知道如何将关联数组复制到dict变量。样品用法
$ ./script.sh 20170707 a
20170707 falls in the range of a
1 个解决方案
#1
2
You don't need to copy anything at all; you just need an alias.
你根本不需要复制任何东西;你只需要一个别名。
#!/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
is the bash (4.3+) version of the ksh93 feature nameref
; see http://wiki.bash-hackers.org/commands/builtin/declare#nameref
declare -n是ksh93特性nameref的bash(4.3+)版本;请参阅http://wiki.bash-hackers.org/commands/builtin/declare#nameref
#1
2
You don't need to copy anything at all; you just need an alias.
你根本不需要复制任何东西;你只需要一个别名。
#!/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
is the bash (4.3+) version of the ksh93 feature nameref
; see http://wiki.bash-hackers.org/commands/builtin/declare#nameref
declare -n是ksh93特性nameref的bash(4.3+)版本;请参阅http://wiki.bash-hackers.org/commands/builtin/declare#nameref