Linux echo date format

How to Get Current Date and Time in Bash Script

As a scripting language, Bash is widely used for system administration tasks and automation. One common task in Bash scripting is to get the current date and time. The `date` command returns the current date and time in a specific format, but you can also use a custom format string to get the date and time in any format

In this article, we will explore how to get the current date and time in a Bash script.

Getting the Current Date and Time

In Bash, you can use the date command to get the current date and time. By default, the date command will return the current date and time in the format of “Day_of_week Month Day Hour:Minute:Second Timezone Year”

date Sun Feb 28 23:26:13 UTC 2023

You can also store the output of command in a variable for further use.

Custom Format Output

There are several switches, you can use to format the output of date command.

    Get date time in “MM/DD/YY HH:MM:SS” format:

date +"%Y-%m-%d %T" 2019-03-25 14:40:32

Use Date in Shell Script:

You can simply use date command inside shell script similar to use on the command prompt. Create a bash script getDateTime.sh with the following content.

Now execute the script from command line and watch output.

./getDateTime.sh Current Date is: Mar 25, 2019 Current Date and Time is: 2019-03-25 17:18:19 Current Date and Time is: 2019-03-05 17:18:19 Current Unix epoch time is: 1488541699

Available Options with date Command:

You can find all available options of date command using –help parameter

You will find the output like below with some more options.

  • %% : a literal %
  • %a : locale’s abbreviated weekday name (e.g., Sun)
  • %A : locale’s full weekday name (e.g., Sunday)
  • %b : locale’s abbreviated month name (e.g., Jan)
  • %B : locale’s full month name (e.g., January)
  • %c : locale’s date and time (e.g., Thu Mar 3 23:05:25 2005)
  • %C : century; like %Y, except omit last two digits (e.g., 21)
  • %d : day of month (e.g, 01)
  • %D : date; same as %m/%d/%y
  • %e : day of month, space padded; same as %_d
  • %F : full date; same as %Y-%m-%d
  • %g : last two digits of year of ISO week number (see %G)
  • %G : year of ISO week number (see %V); normally useful only with %V
  • %h : same as %b
  • %H : hour (00..23)
  • %I : hour (01..12)
  • %j : day of year (001..366)
  • %k : hour ( 0..23)
  • %l : hour ( 1..12)
  • %m : month (01..12)
  • %M : minute (00..59)
  • %n : a newline
  • %N : nanoseconds (000000000..999999999)
  • %p : locale’s equivalent of either AM or PM; blank if not known
  • %P : like %p, but lower case
  • %r : locale’s 12-hour clock time (e.g., 11:11:04 PM)
  • %R : 24-hour hour and minute; same as %H:%M
  • %s : seconds since 1970-01-01 00:00:00 UTC
  • %S : second (00..60)
  • %t : a tab
  • %T : time; same as %H:%M:%S
  • %u : day of week (1..7); 1 is Monday
  • %U : week number of year, with Sunday as first day of week (00..53)
  • %V : ISO week number, with Monday as first day of week (01..53)
  • %w : day of week (0..6); 0 is Sunday
  • %W : week number of year, with Monday as first day of week (00..53)
  • %x : locale’s date representation (e.g., 12/31/99)
  • %X : locale’s time representation (e.g., 23:13:48)
  • %y : last two digits of year (00..99)
  • %Y : year
  • %z : +hhmm numeric timezone (e.g., -0400)
  • %:z : +hh:mm numeric timezone (e.g., -04:00)
  • %::z : +hh:mm:ss numeric time zone (e.g., -04:00:00)
  • %. z : numeric time zone with : to necessary precision (e.g., -04, +05:30)
  • %Z : alphabetic time zone abbreviation (e.g., EDT)
Читайте также:  Kali linux wifi sniff

Conclusion

Getting the current date and time in a Bash script is a common task that can be accomplished using the date command. By default, the date command returns the current date and time in a specific format, but you can also use a custom format string to get the date and time in any format you like. By understanding how to use the date command in a Bash script, you can build powerful automation scripts that make use of the current date and time.

Источник

Как работать с датой и временем в Bash с помощью команды date

Команда Date — это внешняя программа bash, которая позволяет устанавливать или отображать системную дату и время. Он также предоставляет несколько вариантов форматирования. Команда Date установлена во всех дистрибутивах Linux по умолчанию.

Введите команду даты в терминал, которая отобразит текущую дату и время.

Изменить системную дату и время Linux

С помощью команды date можно изменить системную дату, время и часовой пояс, и это изменение должно быть синхронизировано с аппаратными часами.

$ date --set="Thu Nov 12 13:06:59 IST 2020" $ hwclock --systohc

Параметры форматирования

Хорошим местом для получения списка параметров форматирования будет справочная страница.

Давайте рассмотрим некоторые из наиболее распространенных параметров форматирования, которые мы будем использовать.

  • Чтобы применить форматирование, используйте «+, а затем «formatter».
  • Чтобы получить список параметров форматирования для GNU\LINUX, взгляните на связанную справочную страницу.
  • Чтобы получить список параметров форматирования для BSD, взгляните на связанную справочную страницу.

Две важные части команды date — это использование формата +% и параметр –date.

Теперь давайте применим форматирование к команде даты. Чтобы применить форматирование, добавьте знак плюса (+) , а затем %formatter , как показано в примерах.

Дата обработки в Linux

Давайте посмотрим, как использовать средства форматирования, связанные с датой, в простом сценарии оболочки под названием «date.sh».

# PRINT YEAR,MONTH,DAY AND DATE. echo "We are in the year = $(date +%Y)" echo "We are in the year = $(date +%y)" # Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year. echo "We are in the month = $(date +%m)" echo "We are in the month = $(date +%b)" echo "We are in the month = $(date +%B)" # Difference between %B and %b is, %B will print full month name while %b will print abbreviated month name. echo "Current Day of the month = $(date +%d)" echo "Current Day of the week = $(date +%A)" echo "Current Day of the week = $(date +%a)" # Difference between %A and %a is, %A will print full Weekday name while %a will print abbreviated weekday name. # Instead of formatting to get the date, we can use %D which will print the date as %m/%d/%y or %F which prints in %Y-%M-%d format. echo "Date using %D = $(date +%D)" echo "Date using %F = $(date +%F)"

Время обработки в Linux

Давайте посмотрим, как использовать средства форматирования, связанные с временем, в простом сценарии оболочки под названием «time.sh».

# PRINT HOURS, MINS, SECONDS, NANO SECONDS echo Hours = $(date +%H) echo Minutes = $(date +%M) echo Seconds = $(date +%S) echo Nanoseconds = $(date +%N) echo Epoch Time = $(date +%s) echo "current time = $(date +%H:%M:%S:%N)" # can also use %T which displays Time in HH:MM:SS format. echo "current time in 24 hour format = $(date +%T)" # can also use %r to display time in 12 hour format. echo "current time in 12 hour format = $(date +%r)"

С флагом —date или -d

С помощью флага —date или -d ввод может быть передан как строка, и команда date знает, как с этим справиться.

Читайте также:  Lwp and lwp in linux

Давайте посмотрим на несколько примеров, чтобы понять, как это работает.

# Print yesterday's date and time. echo "Yesterday = $(date -d "Yesterday")" # Print Tomorrow date and time. echo "tomorrow = $(date -d "tomorrow")" # Find what is the date and time before 10 days from now. echo "Before 10 days = $(date -d "tomorrow -10 days")" # Find last month and next month echo "Last month = $(date -d "last month" "%B")" echo "Next month = $(date -d "next month" "%B")" # Find last year and next year echo "Last Year = $(date -d "last year" "+%Y")" echo "Next Year = $(date -d "next year" "+%Y")" # Forecast the weekday echo "2 days away from today and it comes on weekdays? = $(date -d "Today +2 days" "+%A")

Общие операции

вычислить количество дней между двумя заданными датами.

$ echo $(( ( $(date -d "2020-11-10" "+%s") - $(date -d "2020-11-01" "+%s") ) / 86400))

Найдите данный год високосным или нет.

$ for y in ; do date -d $y-02-29 &>/dev/null && echo $y is leap year; done

Присвоение вывода команды даты переменной.

$ TODAY=$(date +%Y-%m-%d) OR $ TODAY1=$(date +%F) $ echo $TODAY $ echo $TODAY1

Создайте файлы журнала с датой, добавленной к имени файла.

Добавление даты и времени при создании файлов журналов, резервных копий или текстовых файлов — это обычная операция, с которой мы сталкиваемся чаще всего. Возьмем пример, чтобы сделать резервную копию, мы создали сценарий оболочки.

Этот скрипт будет делать резервную копию с 00:00 до 23:59 и запускаться ежедневно в 00:00 следующего дня. Мы хотим создать файлы журналов со вчерашним форматом даты.

CUSTOM_FORMAT=$(date —date «Yesterday» «+%d-%y-%H:%M») LOG_FILE=/var/log/custom_application/application_$.log echo «Script started» >> $ . CODE BLOCKS . echo «Script completed» >> $

Это все для этой статьи. В этой статье мы увидели, как использовать дату и время bash в Linux. Дайте нам знать ваши отзывы.

Источник

Format date and time for Linux shell script or variable

There are many times you need to use date in your shell script e.g. to name log file, to pass it as a variable, etc. So we need a different format of dates that can be used as a string or variable in our scripts. In this article, let’s see how to use date in shell script and what all different types of formats you can use.

Читайте также:  Linux mint график релизов

How to use date in shell script?

You can use the date by inserting shell execution within the command. For example, if you want to create a log file by inserting the current date in it, you can do it by following way –

root@kerneltalks # echo test > /tmp/`date +%d`.txt root@kerneltalks # ls -lrt -rw-r--r--. 1 root root 5 Sep 10 09:10 10.txt

Basically you need to pass format identifier with +% to date command to get your desired format of the output. There is a different identifier date command supply.

You can even save specific date format to some variable like –

root@kerneltalks # MYDATE=`date +%d.%b.%Y` root@kerneltalks # echo $MYDATE 10.Sep.2018

Different format variables for date command

These format identifiers are from date command man page :

%a locale’s abbreviated weekday name (e.g., Sun) %A locale’s full weekday name (e.g., Sunday) %b locale’s abbreviated month name (e.g., Jan) %B locale’s full month name (e.g., January) %c locale’s date and time (e.g., Thu Mar 3 23:05:25 2005) %C century; like %Y, except omit last two digits (e.g., 20) %d day of month (e.g, 01) %D date; same as %m/%d/%y %e day of month, space padded; same as %_d %F full date; same as %Y-%m-%d %g last two digits of year of ISO week number (see %G) %G year of ISO week number (see %V); normally useful only with %V %h same as %b %H hour (00..23) %I hour (01..12) %j day of year (001..366) %k hour ( 0..23) %l hour ( 1..12) %m month (01..12) %M minute (00..59) %N nanoseconds (000000000..999999999) %p locale’s equivalent of either AM or PM; blank if not known %P like %p, but lower case %r locale’s 12-hour clock time (e.g., 11:11:04 PM) %R 24-hour hour and minute; same as %H:%M %s seconds since 1970-01-01 00:00:00 UTC %S second (00..60) %T time; same as %H:%M:%S %u day of week (1..7); 1 is Monday %U week number of year, with Sunday as first day of week (00..53) %V ISO week number, with Monday as first day of week (01..53) %w day of week (0..6); 0 is Sunday %W week number of year, with Monday as first day of week (00..53) %x locale’s date representation (e.g., 12/31/99) %X locale’s time representation (e.g., 23:13:48) %y last two digits of year (00..99) %Y year %z +hhmm numeric timezone (e.g., -0400) %:z +hh:mm numeric timezone (e.g., -04:00) %::z +hh:mm:ss numeric time zone (e.g., -04:00:00) %Z alphabetic time zone abbreviation (e.g., EDT)

Using combinations of above you can get your desired date format as output to use in shell script! You can even use %n for new-line and %t for adding a tab in outputs that are mostly not needed since you will be using it as a single string.

Different date format examples

For your convenience and ready to use, I listed below combinations for different date formats.

root@kerneltalks # date +%d_%b_%Y 10_Sep_2018 root@kerneltalks # date +%D 09/10/18 root@kerneltalks # date +%F-%T 2018-09-10-11:09:51 root@kerneltalks # echo today is `date +%A` today is Monday root@kerneltalks # echo Its `date +%d` of `date +%B" "%Y` and time is `date +%r` Its 10 of September 2018 and time is 11:13:42 AM

Источник

Оцените статью
Adblock
detector