我已经测试了我需要的格式,但我无法获得回声输出,请尝试将引号放在不同的位置。
[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'
预期输出
July 29 21:01:24.766: %LINK-3-UPDOWN: Interface Port-channel1, changed state to up'
你可以做:
tm=$(date '+%B %V %T.%3N:')
echo "${tm} %LINK-3-UPDOWN: Interface Port-channel1, changed state to up"
打印:
July 29 09:22:23.3N: %LINK-3-UPDOWN: Interface Port-channel1, changed state to up
注意双"
与单'
。只有双引号中的字符串才会插入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}
如果你想把整件事放在一行:
echo "$(date '+%B %V %T.%3N:') %LINK-3-UPDOWN: Interface Port-channel1, changed state to up"
或者修改您的date
格式字符串:
date '+%B %V %T.%3N: %%LINK-3-UPDOWN: Interface Port-channel1, changed state to up'
您实际上并不需要echo
。让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
从技术上讲,如果你愿意牺牲时间戳中的几分之一秒,你甚至不需要date
:
$ printf '%(%B %V %T)T %sn' -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
在实现printf
时不支持%N
。%(...)T
根据...
格式化整数秒,-1
表示当前时间。(
单引号内的字符始终是一个静态字符串。如果你想执行shell命令,你需要一个命令替换,通常在双引号内:
echo "$(date ’+%B %V %T.%3N:’) %LINK-3-UPDOWN: Interface Port-channel1, changed state to up"
然而,这基本上只是对echo
的无用使用。
date ’+%B %V %T.%3N: %%LINK-3-UPDOWN: Interface Port-channel1, changed state to up'
请注意,您需要如何将date
格式字符串中的任何文字%
字符加倍。