Bash date returns current date when datestring is null

时间:2017-12-18 05:23:06

标签: bash unix

date -d 'datestring' -- returns current date in the shell script when datestring is null/empty. But I want to fail the script when datestring is null. Sure, I can put a condition just above this line of code to check whether datestring is null. But, Is there a way to check in the date line itself?

1 个答案:

答案 0 :(得分:1)

The shell has syntax for exiting when a variable is empty or unset:

: ${datestring:?cannot be empty}

and for specifying a value if one hasn't been supplied:

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

Without a colon in the operator, these check only for an unset variable (it's okay for it to be set but empty). The original Bourne shell only had the colonless variant, and you had to check for an empty value separately.

The ${var:?error message string} and colonless ${var?error message string} will cause a script to exit with the message in the error message string if the variable is (empty or) unset. If you use these interactively, the interactive shell won't exit, but you still get the error message, and $? will be set to a nonzero number to communicate the error in a machine-readable form.