简体   繁体   English

如何向bash脚本添加时间戳?

[英]How to add a timestamp to bash script?

I am running a script to check for security vulnerabilities.我正在运行一个脚本来检查安全漏洞。 How do I add a timestamp to the script with results going into a file in /var/log/security-check如何将时间戳添加到脚本中,结果将进入 /var/log/security-check 中的文件

#!/bin/sh

# watch accounts - keep an eye on /etc/passwd,
#                  report if accounts change

secretcopy="$HOME/.watchdb"
tempfile="$HOME/.watchdb.new"
passwd="/etc/passwd"
compare=0               # by default, don't compare

trap "/bin/rm -f $tempfile" 0

if [ -s "$secretcopy" ] ; then
  lastrev="$(cat $secretcopy)"
  compare=1
fi

cat $passwd | cut -d: -f1 > $tempfile

current="$(cat $tempfile)"

if [ $compare -eq 1 ] ; then
  if [ "$current" != "$lastrev" ] ; then
    echo "WARNING: password file has changed"
    diff $secretcopy $tempfile | grep '^[<>]' |
        sed 's/</Removed: /;s/>/Added:/'
  fi
else
   mv $tempfile $secretcopy
fi

exit 0

Every file when modified gets timestamped.修改后的每个文件都带有时间戳。 You can do a ls -l to check that.您可以执行ls -l来检查。 Also if you need to timestamp any file, just use touch.此外,如果您需要为任何文件添加时间戳,只需使用 touch。 touch creates if it doesn't exist.如果它不存在,则触摸创建。 If it exists, timestamp of that script that you passed to it will be updated to latest time.如果存在,您传递给它的脚本的时间戳将更新为最新时间。

If you want to add time stamp to a file separately, use:如果要单独向文件添加时间戳,请使用:

date +"%T” > "filename"

This post adds some more detail to the answer. 这篇文章为答案添加了更多细节。

If you want to get a file to be stamped to latest time:如果您想将文件标记为最新时间:

touch filename

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

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