Linux echo date format

Команда Date в Linux с примерами

Linux Date Command with Examples

В этом руководстве мы рассмотрим основы date команды.

Команда date отображает или устанавливает системную дату. Чаще всего он используется для печати даты и времени в разных форматах и ​​для расчета будущих и прошлых дат.

Использование Date

Синтаксис date команды следующий:

Выходные данные включают день недели, месяц, день месяца, время, часовой пояс и год:

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

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

Символ %Y будет заменен на год, %m месяц и %d день месяца:

Вот еще один пример:

Ниже приведен небольшой список некоторых наиболее распространенных символов форматирования:

  • %a — Сокращенное название дня недели (например, понедельник)
  • %A — Сокращенное полное название дня недели (например, понедельник)
  • %b — Сокращенное название месяца (например, январь).
  • %B — сокращенное длинное название месяца (например, январь)
  • %d — день месяца (например, 01)
  • %H — час (00..23)
  • %I — час (01.12.12)
  • %j — День года (001..366)
  • %m — Месяц (01.12.12)
  • %M — Минута (00..59)
  • %S — Второй (00 .. 60)
  • %u — день недели (1..7)
  • %Y — Полный год (например, 2019)

Чтобы получить полный список всех параметров форматирования, запустите date —help или man date в своем терминале.

Пользовательское форматирование даты

-d Опция позволяет работать на дату конкретного. Вы можете указать дату в виде удобочитаемой строки даты, как показано ниже:

Использование пользовательского форматирования:

Строка даты принимает значения, такие как «завтра», «пятница», «последняя пятница», «следующая пятница», «следующий месяц», «следующая неделя» .. и т. Д.

Вы также можете использовать параметр строки даты, чтобы показать местное время для разных часовых поясов. Например, чтобы показать местное время 6:30 утра следующего понедельника на восточном побережье Австралии, введите:

Переопределить часовой пояс

Команда date возвращает дату в системном часовом поясе по умолчанию . Чтобы использовать другой часовой пояс, установите переменную среды TZ в желаемый часовой пояс.

Например, чтобы показать время в Мельбурне, введите:

Чтобы получить список всех доступных часовых поясов , вы можете либо перечислить файлы в /usr/share/zoneinfo каталоге, либо использовать timedatectl list-timezones команду.

Конвертер эпох

date Команда может быть использована в качестве преобразователя Epoch. Время, или метки времени Unix, — это количество секунд, прошедших с 1 января 1970 года в 00:00:00 UTC.

Чтобы напечатать количество секунд от эпохи до текущего дня, вызовите date с %s контролем формата:

Чтобы преобразовать секунды с начала эпохи в дату, установите секунды в виде строки даты с префиксом @ :

Использование date с другими командами

Команда date чаще всего используется для создания имен файлов, которые содержат текущее время и дату.

Команда ниже создаст файл резервной копии Mysql в следующем формате database_name-20190601.sql

Вы также можете использовать date команду в своих сценариях оболочки. В приведенном ниже примере мы присваиваем выход date к date_now переменной:

Показать время последнего изменения файла

Команда date с -r параметром показывает время последнего изменения файла. Например:

Если вы хотите изменить временную метку файла, используйте touch команду .

Установите системное время и дату

Установка системного времени и даты вручную с помощью этой date команды не рекомендуется, поскольку в большинстве дистрибутивов Linux системные часы синхронизируются с ntp помощью systemd-timesyncd служб или .

Однако, если вы хотите установить системные часы вручную, вы можете использовать эту —set= опцию. Например, если вы хотите установить дату и время 17:30, 01 июня 2019 г., введите:

Читайте также:  Windows forward port netsh

Вывод

Команда Linux date отображает или устанавливает системную дату и время.

Источник

How To Get / Print Current Date in Unix / Linux Shell Script

H ow do I get the current date in Unix or Linux shell scripting and store it into a shell variable? How do I print the current date using Unix shell script? How can I display the current time in Linux shell script?

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux or Unix
Est. reading time 3 minutes

You need to use the following syntax to print current date and time on screen:

To store current date and time to a variable, enter:
now=$(date)
OR
now=`date`

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

To print this date either use the printf or echo statement:
echo «$now»
echo «Current date: $now»
OR use the printf command:
printf «%s\n» «$now»
OR
printf «Current date and time in Linux %s\n» «$now»

Getting the current date and time in Linux shell script

You can format and display date using the following syntax:

Finding the current date and time in Linux or Unix using the date command

A list of date command format codes

FORMAT code Description
%% 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., 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, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%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
%q quarter of year (1..4)
%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 time zone (e.g., -0400)
%:z +hh:mm numeric time zone (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)

Sample shell script to display the current date and time

Conclusion

You learned how to display the current date and time on Linux and Unix-like systems. We also explained how to store date or time in a shell variable. For more info see date command man page by typing the following date command or GNU/date help page here:
man date

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How To Format Date For Display or Use In a Shell Script

H ow do I format the date to display on the screen on for my shell scripts as per my requirements on Linux or Unix like operating systems?

You need to use the standard date command to format date or time in Linux or Unix shell scripts. You can use the same command with the shell script. This page shows how to format date in Linux or Unix-based system.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements date on Linux/Unix
Est. reading time 7 minutes

Linux Syntax To Format Date For Display On Screen

The syntax is as follows for the GNU/date and BSD/date command:
date +FORMAT
date +»%FORMAT»
date +»%FORMAT%FORMAT»
date +»%FORMAT-%FORMAT»
An operand with a leading plus ( + ) sign signals a user-defined format string which specifies the format in which to display the date and time. The following examples are tested on GNU/Linux, Apple OS X Unix, and FreeBSD unix operating system.

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +»%m-%d-%y»
Sample outputs:

To turn on 4 digit year display:
$ date +»%m-%d-%Y»
Just display date as mm/dd/yy format:
$ date +»%D»

Task: Display time only

Type the following command:
$ date +»%T»
Sample outputs:

To display locale’s 12-hour clock time, enter:
$ date +»%r»
Sample outputs:

To display time in HH:MM format, type:
$ date +»%H-%M»
Sample outputs:

How do I save time/date format to the shell variable?

Simply type the following command at the shell prompt to get the current date in MM-DD-YYYY format:
$ NOW=$(date +»%m-%d-%Y»)
To display a variable use the following simple commands to output on screen under Linux and UNIX using the printf command/echo command:
$ echo «$NOW»
printf «%s\n» $NOW

A sample shell script

A complete list of FORMAT control characters supported by the GNU/date command

It can be the combination of any one of the following:

Table 1 – FORMAT controls the output for Linux

%FORMAT String Description
%% 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)

A complete list of FORMAT control characters supported by the BSD/date command

The following works on Apple macOS/OS X, FreeBSD and *BSD version of the date command:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Table 2 – BSD/date command
%FORMAT String Description
%A is replaced by national representation of the full weekday name.
%a is replaced by national representation of the abbreviated weekday name.
%B is replaced by national representation of the full month name.
%b is replaced by national representation of the abbreviated month name.
%C is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
%c is replaced by national representation of time and date.
%D is equivalent to “%m/%d/%y”.
%d is replaced by the day of the month as a decimal number (01-31).
%E* %O* POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations.
Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).
%e is replaced by the day of the month as a decimal number (1-31); single digits are preceded by a blank.
%G is replaced by a year as a decimal number with century. This year is the one that contains the greater part of the week (Monday as the first day of the week).
%g is replaced by the same year as in “%G”, but as a decimal number without century (00-99).
%H is replaced by the hour (24-hour clock) as a decimal number (00-23).
%h the same as %b.
%I is replaced by the hour (12-hour clock) as a decimal number (01-12).
%j is replaced by the day of the year as a decimal number (001-366).
%k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
%l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
%M is replaced by the minute as a decimal number (00-59).
%m is replaced by the month as a decimal number (01-12).
%n is replaced by a newline.
%O* the same as %E*.
%p is replaced by national representation of either “ante meridiem” (a.m.) or “post meridiem” (p.m.) as appropriate.
%R is equivalent to “%H:%M”.
%r is equivalent to “%I:%M:%S %p”.
%S is replaced by the second as a decimal number (00-60).
%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
%T is equivalent to “%H:%M:%S”.
%t is replaced by a tab.
%U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
%u is replaced by the weekday (Monday as the first day of the week) as a decimal number (1-7).
%V is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last week of the previous year, and the next week is week 1.
%v is equivalent to “%e-%b-%Y”.
%W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00-53).
%w is replaced by the weekday (Sunday as the first day of the week) as a decimal number (0-6).
%X is replaced by national representation of the time.
%x is replaced by national representation of the date.
%Y is replaced by the year with century as a decimal number.
%y is replaced by the year without century as a decimal number (00-99).
%Z is replaced by the time zone name.
%z is replaced by the time zone offset from UTC; a leading plus sign stands for east of UTC, a minus sign for west of UTC, hours and minutes follow with two digits each and no delimiter between them (common form for RFC 822 date headers).
%+ is replaced by national representation of the date and time (the format is similar to that produced by date(1)).
%-* GNU libc extension. Do not do any padding when performing numerical outputs.
%_* GNU libc extension. Explicitly specify space for padding.
%0* GNU libc extension. Explicitly specify zero for padding.
%% is replaced by %.

A sample date session

I am running commands on macOS/OS X and FreeBSD:

Источник

Читайте также:  Windows 10 не находит принтер zebra
Оцените статью