我这里有一个脚本,它将列出用户输入的日期并输出 5 天前的日期。
#!/bin/bash
echo "What month?"
echo "1 - January"
echo "2 - February"
echo "3 - March"
echo "4 - April"
echo "5 - May"
echo "6 - June"
echo "7 - July"
echo "8 - August"
echo "9 - September"
echo "10 - October"
echo "11 - November"
echo "12 - December"
echo ""
echo -n "What month? "
read m
if [ "$m" == "1" ]
then
mn="Jan "
elif [ "$m" == "2" ]
then
mn="Feb "
elif [ "$m" == "3" ]
then
mn="Mar "
elif [ "$m" == "4" ]
then
mn="Apr "
elif [ "$m" == "5" ]
then
mn="May "
elif [ "$m" == "6" ]
then
mn="Jun "
elif [ "$m" == "7" ]
then
mn="Jul "
elif [ "$m" == "8" ]
then
mn="Aug "
elif [ "$m" == "9" ]
then
mn="Sep "
elif [ "$m" == "10" ]
then
mn="Oct "
elif [ "$m" == "11" ]
then
mn="Nov "
elif [ "$m" == "12" ]
then
mn="Dec "
else
echo "Invalid month"
fi
echo ""
#DAY
echo -n "What day? "
read d
if [ "$d" -lt "9" ]
then
mnd="$mn"" ""$d"
elif [ "$d" -gt "31" ]
then
mnd="1"
else
mnd="$mn""$d"
fi
for dy in {0..4}; do
date -d "$mn $d - $dy days" +'%b %_d'
done
输出:
What month?
8
What day?
1
Aug 1
Jul 31
Jul 30
Jul 29
Jul 28
我现在想要的是将每个日期存储到变量中,例如第一行必须Aug 1
存储在变量中x1
Jul 31
必须存储在变量中x2
等等。我的意思是第一个列表上的任何输出都必须存储在x1
等等。
答案1
使用数组而不是尝试创建单独的变量。
declare -a x
for dy in {0..4}; do
x+=( "$( date -d "$mn $d - $dy days" +'%b %_d' )" )
done
${x[0]}
然后,您可以访问到中的四个值${x[3]}
。
对于脚本的第一部分,您是否考虑过使用select
语句?
select mn in "Jan" "Feb" "Mar" "Apr" "May" "Jun" \
"Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
do
if [[ -z "$mn" ]]; then
echo "Invalid choice" >&2
else
break
fi
done
printf "You selected '%s'\n" "$mn"
这会执行以下操作:
1) Jan 3) Mar 5) May 7) Jul 9) Sep 11) Nov
2) Feb 4) Apr 6) Jun 8) Aug 10) Oct 12) Dec
#? 56
Invalid choice
#? 5
You selected 'May'
的值$mn
将是选定的字符串(May
例如)。