adding date and variable name to log file and generate a new one

I am trying to run a bash script on daily basis which generates a log file.

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>logfile.output 2>&1

present_date="`date +"%Y-%m-%d-%H-%M-%S"`"
echo -e "33[0;36mpresent_date:33[0m $present_date"

) | tee -a /home/eksinvi/output/pm/NSN/NFV/InterfaceStatistics/logs/$OSS_NAME-logfile-$present_date-output

bash "Interface"

I am expecting that each time it creates a new log file and have a dynamic name with date and input variable name on it.

Asked By: vikrant rana


Take out the subshell ( and ) (which create a child process of the script). Also remove the extra quotes around the date command:



present_date=$(date +%Y-%m-%d-%H-%M-%S)
echo -e "33[0;36mpresent_date:33[0m $present_date" | tee -a /home/eksinvi/output/pm/NSN/NFV/InterfaceStatistics/logs/$OSS_NAME-logfile-$present_date-output

The variable $present_day was being populated with the date/time string in the child process (the subshell), but tee in the parent process needed the value to create the timestamped filename. Child processes can inherit the values of variables from parent processes, but parents can’t inherit from the children. My version above does both of these in the same process.

If the echo command here is just a test version, and your goal is to have several commands in a subshell that are piped to tee, then start the subshell after the $present_date variable is populated. The subshell’s commands will have the value available to them, and so will the parent process’s tee command.

I also removed the file descriptor swapping at the start of the script, because tee writes to its stdout as well as the file in its -a argument, and the file descriptor swapping was redirecting this to the logfile.output file in the current directory, which you probably don’t want.

Answered By: Sotto Voce
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.