用BC bash计算天数

时间:2015-04-11 05:25:34

标签: bash bc

所以我的剧本必须计算某人将从旅行中返回的日子。用于使用用户输入计算离开日期和行程长度。每天都有一定数量,如周一1;星期二等等,但是当星期日的用户输入必须为0时,它会变得复杂。

脚本atm我做了什么:

#!/bin/bash
#Data
echo -e "\e[00;31mRemember!\e[00m Sunday-0; Monday-1; Tuesday-2; Wednesday-3; Thursday-4; Friday-5; Saturday-6;"
echo
echo -n "What day will you leave? "
read left
echo -n "How long is your trip? "
read days
#Calculating
cb=`echo "$left+$days" | bc`
comeback=`echo "$cb % 6" | bc`
#Output
if [ $comeback = 0 ]; then
echo "You will be back at Sunday"
fi
if [ $comeback = 1 ]; then
echo "You will be back at Monday"
fi
if [ $comeback = 2 ]; then
echo "You will be back at Tuesday"
fi
if [ $comeback = 3 ]; then
echo "You will be back at Wednesday"
fi
if [ $comeback = 4 ]; then
echo "You will be back at Thursday"
fi
if [ $comeback = 5 ]; then
echo "You will be back at Friday"
fi
if [ $comeback = 6 ]; then
echo "You will be back at Saturday"
fi

我的问题是,当旅行超过一周或者应该在周日结束时,它永远无法计算。 当我开始像星期日一样计算时,我的脚本正常工作;星期一2等,但星期日必须是0。

1 个答案:

答案 0 :(得分:1)

更正您的剧本:

comeback=$(echo "(${left} + ${days}) % 7" | bc)

此外,您应该使用数组进行输出:

days_of_week=( Sunday Monday Tuesday Wednesday Thursday Friday Saturday )
echo "You will be back on ${days_of_week[${comeback}]}"

我还想指出一个有趣的答案。使用GNU coreutils中的date,您可以在阅读$left$days之后执行此操作:

echo "You will be back on $(date -d "${days_of_week[${left}]} + ${days} days" +%A)"