Current Hour

To get current hour in Bash script, use date command with the format that outputs only the hour value.

There are two different types of format in which we could get hour from the date command. They are

  • 24 Hour Format
  • 12 Hour Format

In this tutorial, we will learn the syntax to get the current hour in the above said formats, with examples.

Syntax

The syntax of date command to get current hour in 24 hour format is

date +%H

The syntax of date command to get current hour in 12 hour format is

date +%I
ADVERTISEMENT

Examples

Current Hour – 24 Hour Format

In the following script, we get current hour in 24 hour format and echo it to the standard console.

Example.sh

hours=$(date +%H)
echo "Hours : $hours"

Output

Hours : 13

Current Year – 12 Hour Format

In the following script, we get current hour in 12 hour format and echo it to the standard console.

Example.sh

hours=$(date +%I)
echo "Hours : $hours"

Output

Hours : 01

Conclusion

In this Bash Tutorial, we have learnt how to get current year in Bash Script using date command.