KItis
KItis

Reputation: 5646

What does this bash script function does

I am new to shell scripting and i found this function in a given script file.

##############################
# rotate_daily(filename)
rotate_daily() {
  _code=0
  _file_src=$1

  _today=`date '+%Y-%m-%d'`
  _file_dest=${_file_src}.${_today}
  if [ -f ${_file_dest} ]; then
    printk "rotate_daily(): ${_file_dest} already exist"
    _code=1
  else
    if [ -f ${_file_src} ]; then
      printk "rotate_daily(): ${_file_src} => ${_file_dest}"
      cp -p ${_file_src} ${_file_dest}
      _code=$?
      >${_file_src}
    fi
  fi
}

I understand this is kind of coping file from one location to another location. But, it is not rotating right?. could somebody explain me what it is really does.

thanks in advance for any help

Upvotes: 0

Views: 87

Answers (2)

William Pursell
William Pursell

Reputation: 212248

If the time stamped file already exists, this code snippet does nothing but print a message via printk indicating that. If it does not exist, it copies the source file to it and truncates the source file. I would guess that the line you are not quite understanding is:

>${_file_src}

That line truncates the original file after it has been copied. Note that there is a race condition, and any data written to the file between the copy and the truncation will be lost.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

It copies _file_src to the location file_dest unless _file_dest already exists. An informative message will be printed that tells you if the file already exists or file_src_ will be copied, It also moves _file_src only if it is a file.

EDIT: forgot to mention what the command >{_file_src} does - it simply wipes out the contents of the source file. So you will have the contents of _file_src moved to file_dest in the end and _file_src will be empty. I can't figure why not simply do a move(with mv) and then create an empty file, but that's your question.

Upvotes: 1

Related Questions