Wednesday, February 7, 2024

[SOLVED] Writing script so it will save command output and save it as different text with date stamp

Issue

This is my first scripting attempt and what I need to do is monitor partitions on my CentOS 7 server. So what I want to do is execute the df -h command and save the output to the file every hour.

I have read up on the cron jobs etc. and don't have a problem with that. The problem I am facing is the physical script I have to write.

I want the command to run df -h and save the output with a date stamp if possible to a NEW txt file or just to add to the same file as long as the date stamp is there I can go and review it later. I have created a .sh file and in there i have

#!/bin/sh
df -h | more filename.txt

At the moment all am getting is the following - I have tried adding date commands but no joy.

script output


Solution

The following example shows different ways how you could use the command date within a function() to echo the date into a file together with another command output, as well how you could create new filenames with timestamp.

#!/bin/bash

timestamp() {
  echo -n $(date +"%Y-%m-%d %T")
}

echo -e "$(timestamp)\n$(df -h)" > diskusage.$(date +"%Y%m%d%H%m").log


Answered By - U880D
Answer Checked By - Cary Denson (WPSolving Admin)