根据条件更改变量

时间:2012-11-23 21:21:57

标签: macos bash

这个问题与这里的主题有关:

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

2 个答案:

答案 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

来避免八进制问题