Linux / Unix Shell Scripting: Create Filename By Day Of The Week

I need to create a log file using the following format:

ADVERTISEMENTS

myapp_monday.log
myapp_tuesday.log
….

myapp_sunday.log

How do I create log filename with day of the week in it under Linux or Unix operating systems?

You can use the date command to display current date and time. You can format a date provide a string beginning with + to get day of the week as follows:
$ date +"%A"
Where,

  • +”%A” – Get weekday in full format i.e. as Tuesday
  • +”%a” – Get weekday in abbreviated format i.e. as Tue
  • +”%u” – Get day of week starting with Monday (1), i.e. mtwtfss
  • +”%w” – Get day of week starting with Sunday (0), i.e. smtwtfs

Use the following syntax to store weekday into a shell variable:

 
_dow="$(date +'%A')"
echo "$_dow"
 
## Get day of week starting with Monday (1), i.e. mtwtfss  (see above for syntax) ##
_dow="$(date +'%u')"
echo "$_dow"

To create a filename with day of the week in it:

#!/bin/bash
 
_dow="$(date +'%A')"
_log="myapp_${_dow}.log"
echo "My log filename: ${_log}"

Sample outputs:

My log filename: myapp_Wednesday.log
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
3 comments… add one
  • Christian Jul 21, 2014 @ 7:03

    Thx for your help! Works perfect!

  • mahesh Mar 14, 2016 @ 7:25

    why you have used -dow and -log it’s varabiles

    • Gurbaksh Singh May 10, 2016 @ 12:34

      @ Mahesh: _dow & _log are just variable names here that represents the data inside is as dayofweek and logs type :)

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.