SaranyaR
SaranyaR

Reputation: 55

Print a Date with some text in a new File using Shell Script

I'm new to the Shell script.

I want to create a file using shell script and write a current date and time in that file. So i tried the below code. It is creating the Text file successfully and writing the text but not the date. I don't know what did i miss. Any help would be appreciated.

echo $(date) : New Log File Created > Output.txt
echo $(date) : Exiting the program >> Output.txt

It is just printing the output as is like

"$(date) : New Log File Created"

Upvotes: 3

Views: 9685

Answers (1)

Dexirian
Dexirian

Reputation: 575

First of all you will want to format the output of date if you want to use it in the filename. If not you can use standard date command. You can find date format explanations here

Here is a sample block of code to output the current date and time to a text file :

#!/bin/bash

echo $(date +%F-%T) >> Output.txt

Here %F outputs the full date in the following format : YYYY-MM-DD

And %T outputs time in the following format : HH:MM:SS

If you want to add more text than just the date, you can use the " delimiter, to create a string as follow :

echo "$(date +%F-%T) Log output" >> Output.txt

Putting all the text in the string makes sure bash doesn't interpret what's inside the string as operators and delimiters.

EDIT : Screenshot for bash version :

Bash version example

Upvotes: 5

Related Questions