这个问题与这里的主题有关:
Today's date, minus X days in shell script
但是因为我现在正在操纵变量,所以我开始了另一个线程。
如上所述,我需要将今天的日期减去200天,将年,月和日分开为单独的变量(在这个问题中,我将使用200,尽管在另一个中它是222)。但是,我需要将1月份表示为0,将2月份表示为1(或01),将3月份表示为2(或02)等...我试过这个:
MONTHS200=$(date -j -v-200d -v-1m +"%m")
if ${MONTHS200}=01; then
${MONTH200}=0
else ${MONTHS200}=${MONTH200}
fi
但我收到错误./update_newdateformat.sh: line 20: 12=01: command not found ./update_newdateformat.sh: line 23: 12=: command not found
-v-1m
适用于除1月以外的所有月份,因为它会转到12,而不是0
答案 0 :(得分:2)
以下是如何将所有月份数减少1个脚本:
MONTHS200=$(date -j -v-320d +"%m")
# Remove leading zero if there is one, so it doesn't cause problems later
MONTHS200=${MONTHS200#0}
MONTHS200=$((MONTHS200-1))
以下是在shell中使用if
和=
(赋值)语法的方法:
if [[ "${MONTHS200}" == "01" ]]; then
MONTHS200="0"
else
MONTHS200=${AnotherVariable}
fi
请注意,对于数字比较,您需要使用:
-eq
代替==
-ne
代替!=
-lt
代替<
-le
代替<=
-gt
代替>
-ge
代替>=
例如:
if [[ "${MONTHS200}" -eq 1 ]]; then
答案 1 :(得分:1)
我会利用bash功能(我认为OSX bash已经足够了 - 我可能错了)。您只需使用
拨打date
一次
read year month day < <(date -j -v-200d +"%Y %m %d")
month=$(( 10#$month - 1 ))
通过强制bash使用base-10
来避免八进制问题