简体   繁体   中英

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

#!/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. Also if you need to timestamp any file, just use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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