bash echo time date format

Viewed 2070

I have tested the format I need however I am unable to get the echo output, try put the quote around the different position.

[root@]# date '+%B %V %T.%3N:'
July 29 21:01:24.766:
echo 'date ’+%B %V %T.%3N:’ %LINK-3-UPDOWN: Interface Port-channel1, changed state to up'

expected output

July 29 21:01:24.766: %LINK-3-UPDOWN: Interface Port-channel1, changed state to up'
3 Answers

You can do:

tm=$(date '+%B %V %T.%3N:')
echo "${tm} %LINK-3-UPDOWN: Interface Port-channel1, changed state to up"

Prints:

July 29 09:22:23.3N: %LINK-3-UPDOWN: Interface Port-channel1, changed state to up

Note the double " vs single '. Only strings in double quotes are interpolated in the shell:

bash-5.1$ s1='hello'
bash-5.1$ s2='there'
bash-5.1$ echo "${s1} ${s2}"
hello there

vs:

bash-5.1$ echo '${s1} ${s2}'
${s1} ${s2}

If you want the whole thing in one line:

echo "$(date '+%B %V %T.%3N:') %LINK-3-UPDOWN: Interface Port-channel1, changed state to up"

Or modify your date format string:

date '+%B %V %T.%3N: %%LINK-3-UPDOWN: Interface Port-channel1, changed state to up'

You don't actually need echo. Let date write everything:

$ date '+%B %V %T.%3N %%LINK-3-UPDOWN: Interface Port-channel1, changed state to up'
July 29 09:34:15.874 %LINK-3-UPDOWN: Interface Port-channel1, changed state to up

Technically, you don't even need date, if you are willing to sacrifice the fraction of a second in the timestamp:

$ printf '%(%B %V %T)T %s\n' -1 "%LINK-3-UPDOWN: Interface Port-channel1, changed state to up"
July 29 09:36:40 %LINK-3-UPDOWN: Interface Port-channel1, changed state to up

(bash doesn't support %N in its implementation of printf. %(...)T formats an integer number of seconds according to ..., with -1 representing the current time.)

Characters inside single quotes are a static string, always. If you want to execute a shell command, you need a command substitution, usually inside double quotes:

echo "$(date ’+%B %V %T.%3N:’) %LINK-3-UPDOWN: Interface Port-channel1, changed state to up"

However, that's basically just a useless use of echo.

date ’+%B %V %T.%3N: %%LINK-3-UPDOWN: Interface Port-channel1, changed state to up'

Notice how you need to double any literal % characters in the date format string.

Related