0

How would a date command output null/nothing when the variable supplied has no/null value. I know if else statement can do this, but I kinda think it's not the proper way. Is there a decent command or alterations to the date command to do this?

E.g.

myDay=""
bDay=`date -d "$myDay"`
echo "$bDay" // this should have no output
2

You could do:

bDay=${myDay:+$(date -d "$myday")}

or:

if [ -n "$myDay" ]; then
  bDay=$(date -d "$myDay")
else
  bDay=
fi

or:

bDay=$([ -z "$myDay" ] || date -d "$myDay")

or (with an error message if $myDay is empty):

bDay=$(date -d "${myDay:?no date supplied}")

Note that echo (except for csh's echo) always outputs at least a newline character (unless you use -n or \c depending on the echo implementation), even when not passed any argument, so you'd also need:

[ -z "$bDay" ] || echo "$bDay"

for not outputting anything when $bDay is empty.

  • I'm using your first suggestion. Thanks a lot! +1 – WashichawbachaW Oct 31 '18 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.