How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Learn how to effortlessly showcase the date and time in your Linux terminal Master the versatile date command, harness its power in shell scripts, and explore a plethora of options to customize the display Enhance your scripting skills and streamline your Linux experience

Some Noticeable Information

The date command in the Bash shell can be used to display the current date and time in various formats, allowing for customization.

The output of the date command can be customized by utilizing the "+" sign and different option codes. This allows for specific details like the day, month, year, or timezone to be included in the formatted output.

In shell scripts, the date command proves to be useful for automating certain tasks. For instance, it can be employed to generate directory names with timestamps or to copy files while retaining specific time information.

The Bash shell, which is the default shell in most Linux distributions and macOS, includes the date command. This tutorial will guide you through mastering the date command on the command line and demonstrate how it can be used in shell scripts for tasks beyond just printing the time.

How to See the Date and Time and Time in the Linux Terminal

Run the date command to see this information. It prints the current date and time for your timezone:

date

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

The default formatting appears a bit odd. Instead of appending the year at the end, after the timezone, it would be more logical to display it after the month and day. However, there is a solution. date offers a plethora of formatting options allowing you to precisely tailor the output according to your preferences. With over 40 choices available, you can easily instruct date to format the output exactly the way you desire.

To print the date and time in the normalized format of your locale, use the option "date +%c".

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

The year now appears in a more natural position in the output.

To display the day (%A), day of the month (%d), and month name (%B) simultaneously, multiple options can be passed to the date command using a format string. Execute the following command:

date +%A%d%B

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

That worked, but it is ugly. No problem, we can include spaces as long as we wrap the entire format string in quotation marks. Note that the + goes outside the quotation marks.

date +"%A %d %B"

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

You can add text to the format string, like this:

date +"Today is: %A %d %B"

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Searching for specific options in the date man page can become tedious when scrolling frequently. To alleviate this, we have categorized the options to simplify navigation and make the search process easier.

Options to Display the Date and Time

%c: Prints the date and time in the format for your locale, including the timezone.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Date

%D: Prints the date in mm/dd/yy format.

%F: Prints the date in yyyy-mm-dd format.

%x: Prints the date in the format for your locale.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Day

%a: Prints the name of the day, abbreviated to Mon, Tue, Wed, etc.

%A: Prints the full name of the day, Monday Tuesday, Wednesday, etc.

%u: Prints the number of the day of the week, where Monday=1, Tuesday=2, Wednesday=3, etc.

%w: Prints the number of the day of the week, where Sunday=0, Monday=1, Tuesday=2, etc.

%d: Prints the day of the month, with a leading zero (01, 02 ... 09) if required.

%e: Displays the day of the month, with a leading space (' 1', ' 2' ... ' 9') when necessary. Apostrophes are not included in the output.

%j: Shows the day of the year, with up to two leading zeroes, if necessary.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Week

%U: Displays the week number of the year, with Sunday as the starting day of the week. Examples include the third week of the year, twentieth week of the year, and so on.

%V: Displays the ISO week number of the year, with Monday as the starting day of the week.

%W: Week number of the year, considering Monday as the first day of the week.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Month

%b or %h: Prints the name of the month abbreviated to Jan, Feb, Mar, etc.

%B: prints the full name of the month, January, February, March, etc.

%m: Prints the number of the month, with a leading zero if required 01, 02, 03 ... 12.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Year

%C: Prints the century without the year. In 2019 it would print 20.

%y: Prints the year as two digits. in 2019 it will print 19.

%Y: Prints the year as four digits.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Time

%T: Prints the time as HH:MM:SS.

%R: Prints the hour and minutes as HH:MM with no seconds, using the 24-hour clock.

%r: Prints the time according to your locale, using the 12-hour clock and an am or pm indicator.

%X: Prints the time according to your locale, using the 24-hour clock. Allegedly. Note that during testing this option behaved exactly as %r does, as shown below. On a Linux machine configured for the UK locale and set to GMT, it printed the time, using the 24-hour clock with no AM or PM indicator, as expected.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display the Hour

%H: Prints the hour 00, 01, 02...23.

%I: Prints the hour using the 12-hour clock, 00, 01, 02 ... 12, with a leading zero if required.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display Minutes

%M: prints the minute, 01, 02, 03 ... 59, with a leading zero if required.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display Seconds

%s: Prints the number of seconds since 1970-01-01 00:00:00, the start of the Unix Epoch.

%S: Prints the seconds, 01, 02, 03 ... 59, with a leading zero if required.

%N: Prints the Nanoseconds.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Display Timezone Information

%z: Prints the time difference between your timezone and UTC.

The %:z format prints the time difference between your timezone and UTC, separated by a : between the hours and minutes. Please note the : between the % sign and z.

The %::z format prints the time difference between your timezone and UTC, separated by a : between the hours, minutes, and seconds. Please note the :: between the % sign and z.

%Z: Prints the alphabetic timezone name.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

%p: Prints the AM or PM indicator in uppercase.

%P: Prints the am or pm indicator in lowercase. Note the quirk with these two options. A lowercase p gives uppercase output, an uppercase P gives lowercase output.

%t: Prints a tab.

%n: Prints a new line.

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Options to Modify Other Options

To enhance the display of other options, you can include these modifiers between the % and the corresponding option letter. To illustrate, if you use %-S, it will eliminate the leading zero for single-digit seconds values.

-: A single hyphen prevents zero padding on single digit values.

_: a single underscore adds leading spaces for single digit values.

0: Provides leading zeroes for single digit values.

^: Uses uppercase, if possible (not all options respect this modifier).

#: Use the opposite to the default case for the option, if possible (not all options respect this modifier).

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Two More Neat Tricks

To retrieve the most recent modification time of a file, utilize the -r (reference) option. It is important to note that this option employs a hyphen (-) rather than a percentage (%) sign and does not necessitate a plus (+) sign. Experiment with this command within your home directory:

Instruction: MUST INCLUDE:

Two More Neat Tricks

at the same position as the provided fragment. Do not remove

Two More Neat Tricks

The placeholder must be preserved and included in the output.

date -r .bashrc

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

The TZ setting allows you to change your timezone for the duration of a single command.

TZ=GMT date +%c

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

Using Date in Scripts

Enabling a Bash shell script to print the current time and date is a simple task. To achieve this, create a text file named gd.sh and include the following code:

#!/bin/bash

TODAY=$(date +"Today is %A, %d of %B")

TIMENOW=$(date +"The current local time is %r")

TIME_UK=$(TZ=BST date +"The time in the UK is %r")

echo $TODAY

echo $TIMENOW

echo $TIME_UK

Type the following command to set the execution permissions and make the script executable.

chmod +x gd.sh

Run the script with this command:

/gd.sh

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

To generate a timestamp, the date command can be utilized. The provided script creates a directory using the timestamp as its name and proceeds to copy all text files from the current folder into it. By regularly executing this script, we can capture a snapshot of our text files. This process will gradually accumulate a succession of folders containing distinct versions of our text files.

Note that this isn't a robust backup system, it's just for illustrative purposes.

Create a text file with the following content, and save it as snapshot.sh.

#!/bin/bash

# Get the current date and time

date_stamp=$(date +"%F-%H-%M-%S")

# Create a directory with the obtained date and time

mkdir "$date_stamp"

# Copy all .txt files from the current folder to the newly created directory

cp *.txt "$date_stamp"

# Display a confirmation message

echo "Text files successfully copied to directory: $date_stamp"

# Exit the script

chmod +x snapshot.sh

Run the script with this command:

/snapshot.sh

How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)

A directory has been created named after the execution date and time of the script. Inside this directory, you will find duplicates of the text files. With some imagination and consideration, even the modest date command can be utilized effectively.

Linux Commands

Files

tar · pv · cat · tac · chmod · grep · diff · sed · ar · man · pushd · popd · fsck · testdisk · seq · fd · pandoc · cd · $PATH · awk · join · jq · fold · uniq · journalctl · tail · stat · ls · fstab · echo · less · chgrp · chown · rev · look · strings · type · rename · zip · unzip · mount · umount · install · fdisk · mkfs · rm · rmdir · rsync · df · gpg · vi · nano · mkdir · du · ln · patch · convert · rclone · shred · srm · scp · gzip · chattr · cut · find · umask · wc · tr

Processes

alias · screen · top · nice · renice · progress · strace · systemd · tmux · chsh · history · at · batch · free · which · dmesg · chfn · usermod · ps · chroot · xargs · tty · pinky · lsof · vmstat · timeout · wall · yes · kill · sleep · sudo · su · time · groupadd · usermod · groups · lshw · shutdown · reboot · halt · poweroff · passwd · lscpu · crontab · date · bg · fg · pidof · nohup · pmap

Networking

netstat · ping · traceroute · ip · ss · whois · fail2ban · bmon · dig · finger · nmap · ftp · curl · wget · who · whoami · w · iptables · ssh-keygen · ufw · arping · firewalld

Editor's P/S

As a Gen Z fan, I find the article "How to Show Date and Time in the Linux Terminal (and Incorporate it in Bash Scripts)" to be informative and straightforward. The guide provides clear instructions on how to display the date and time in the Linux terminal using the date command. The examples provided are concise and easy to follow, making it simple to customize the output according to personal preferences.

Furthermore, the article delves into incorporating the date command in Bash scripts, showcasing its practical applications beyond just printing the time. The use cases presented, such as generating directory names with timestamps and copying files while retaining time information, demonstrate the versatility of the date command in automating tasks and enhancing productivity.

Overall, I appreciate the article's focus on practicality and its well-structured format, making it an accessible resource for both beginners and experienced Linux users.