当datestring为null时,Bash日期返回当前日期

问题描述 投票:0回答:1

date -d'datetring' - 当datestring为null / empty时,返回shell脚本中的当前日期。但是当datetring为null时,我希望失败。当然,我可以在这行代码上面放一个条件来检查datestring是否为null。但是,有没有办法检查日期行本身?

bash unix
1个回答
1
投票

shell具有在变量为空或未设置时退出的语法:

: ${datestring:?cannot be empty}

如果没有提供,则指定一个值:

date -d "${datestring:-now}"

如果运算符中没有冒号,则只检查未设置的变量(可以设置它但是为空)。原始的Bourne shell只有无冒号的变体,你必须分别检查一个空值。

${var:?error message string}和colonless ${var?error message string}将导致脚本在error message string中退出,如果变量是(空或)未设置。如果以交互方式使用这些,交互式shell将不会退出,但仍会收到错误消息,并且$?将设置为非零数字,以便以机器可读的形式传达错误。

© www.soinside.com 2019 - 2024. All rights reserved.