我正在調整a bash script of mine以輸出一天中的某一天的序數部分(st,nd,rd,th)。我試圖將其調整爲在date
命令中的日期模式內使用。一個月中的某天不是一個整數
下面是一個簡單的測試,以確定是否從date
命令月份的一天是一個int:
dayOfMonth=$(date +"%d") && [[ ${dayOfMonth} =~ ^[0-9]+$ ]] && echo ${dayOfMonth} is an int || echo ${dayOfMonth} is NOT an int
輸出是如我所料
01 is an int
現在我把代碼放到一個腳本:
#!/bin/bash
[[ ${1} =~ ^[0-9]+$ ]] && echo ${1} is an int || echo ${1} is NOT an int
似乎確定:
dateTest.sh 12
12 is an int
但是,當我嘗試在date
命令中使用它時,該腳本給了我衝突的輸出。 echo
看到12
但測試是看到%2
date --date='06/12/2012 07:21:22' +"`dateTest.sh %d`"
12 is NOT an int
爲了澄清我的目的,腳本的最終結果將是這樣的:
#!/bin/bash
n=$(date +"%d")
if [ $# -ge 1 ] ; then
n=$1
if ! [[ $n =~ ^[0-9]+$ ]] ; then
echo Arg dateInteger [$dateInteger] must be an integer.
exit 1
fi
fi
if [ $n -ge 11 -a $n -le 13 ] ; then
echo "th"
else
case $(($n%10)) in
1)
echo st
;;
2)
echo nd
;;
3)
echo rd
;;
*)
echo th
;;
esac
fi
,這樣我可以這樣說:
date --date='06/12/2012 07:21:22' +"%A, %d`dateTest.sh %d` of %B %Y, %I:%M:%S %p"
哪會輸出
Tuesday, 12th of June 2012, 07:21:22 AM
完成的腳本重新寫入。感謝來自@GordonDavisson的輸入,我完成了我的腳本重寫:http://pastebin.com/xZ1afqqC。現在它可以輸出一個整數的序數,也可以輸出完全格式化的日期,您可以使用date
中的標準格式字符串,並在序號中加上「%O」。
'請將dayOfMonth = $(日期+ 「%d」)&& [ 「$請將dayOfMonth」 -eq 「$請將dayOfMonth」>的/ dev/null的2>&1] &&回波$ {請將dayOfMonth}是一個int || echo $ {dayOfMonth}不是一個int' –
如果在腳本中添加這樣的作品.... odate ='date --date = '06/12/2012 07:21:22'+「%d」' [[$ odate =〜^ [0-9] + $]] && echo $ odate是一個int || echo $ odate不是int –
謝謝@ DavidC.Rankin - 很好的補充。 –