我需要将当前日期传递给 Linux 命令,该命令将为我提供输出
quarter number
我有两个疑问
date +"%Yq$(expr $(expr $(date -d '-1 month' +%m) - 1) / 3 + 1)"
结果 -> 2015q3(当前季度)
date +"%Y %m" | awk '{q=int($2/4);y=$1;if (q==0){q=4;y=y-1;}; printf("%sq%s\n", y, q);}'
结果 -> 2015q2(上一季度)
您能帮忙修改上述查询以获得所需的结果吗?提前致谢。
答案1
有时 KISS(保持简单)是最简单的答案:
year=$(date +%Y)
case $(date +%m) in
01|02|03) let year=year-1
echo ${year}q4 1 oct $year - 31 dec $year oct nov dec ;;
04|05|06) echo ${year}q1 1 jan $year - 31 mar $year jan feb mar ;;
07|08|09) echo ${year}q2 1 apr $year - 31 jun $year apr may jun ;;
10|11|12) echo ${year}q3 1 jul $year - 31 sep $year jul aug sep ;;
esac
单独使用它们的最简单方法是将它们作为函数添加到您想要调用的 shell 脚本中,例如:
getquarter(){
year=$(date +%Y)
case $(date +%m) in
01|02|03) let year=year-1
qtr="${year}q4" range="1 oct $year - 31 dec $year" months="oct nov dec" ;;
04|05|06) qtr="${year}q1" range="1 jan $year - 31 mar $year" months="jan feb mar" ;;
07|08|09) qtr="${year}q2" range="1 apr $year - 31 jun $year" months="apr may jun" ;;
10|11|12) qtr="${year}q3" range="1 jul $year - 31 sep $year" months="jul aug sep" ;;
esac
}
getquarter
echo "last quarter was $qtr, from $range, for $months"
如果您不能这样做,您可以在调用函数后调用您的脚本并在引号中传递参数:
getquarter(){ ... as above }
getquarter
myscript "$qtr" "$range" "$months"