简体   繁体   English

bash echo 时间日期格式

[英]bash echo time date format

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'

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:注意双"与单' 。只有双引号中的字符串会在 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格式字符串:

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

You don't actually need echo .你实际上并不需要echo Let date write everything:date写一切:

$ 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:从技术上讲,如果您愿意牺牲时间戳中的几分之一秒,您甚至不需要date

$ 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.) bash在它的printf实现中不支持%N%(...)T根据...格式化整数秒, -1表示当前时间。)

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:如果要执行 shell 命令,则需要命令替换,通常在双引号内:

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 .但是,这基本上只是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.请注意您需要如何将date格式字符串中的任何文字%字符加倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM