0

what's the best way in shell to create custom date format and adding any space between the format?

For example the below command for print yesterday date by the format Oct 9

custom_format="$(date -d '-1 day' '+%b %-d')"; echo $custom_format

Now I need to add two spaces between the month and the day but usually not working with me, I tested also to using %t to adding tap space but not working with this format.

custom_format="$(date -d '-1 day' '+%b **spaces here** %-d')"; echo $custom_format
2
1

The issue has nothing to do with the date command itself (just insert the spacing in the format string in whatever way you want). The issue is with the echo and the way that you do not quote the expansion of $custom_format.

When you don't quote $custom_format, the shell will split its value into words based on the characters in $IFS (space, tab and newline by default), and will then perform filename generation (globbing) on the resulting words.

This means that your command echo $custom_format will be transformed into something like echo Oct 9, which is echo invoked with two arguments, regardless how many spaces there are between them, and echo would output each, one after the other, with a single delimiting space in-between.

To get the output you are looking for, use double quotes around $custom_format when calling echo with it as an argument.

See also

0

Thank you Steeldriver, I fixed it by using the below syntax

yesterday_day="$(date -d '-1 day' '+%-d')"
yesterday_month="$(date -d '-1 day' '+%b')"
yesterday="${yesterday_month}   ${yesterday_day}"

and now you can add any spaces you want inside it

1
  • 1
    That's no different from yesterday=$(date -d '-1 day' '+%b <three spaces here> %-d') and is not fixing anything. If you write echo $yesterday unquoted, as in your example, there would be a single space between the month and the day. – mosvy Oct 13 '19 at 11:11

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.