Linux echo date time

need linux equivalent to windows «echo %date% %time% %COMPUTERNAME%»

To get hundredths of seconds, you may need to do some text processing like this:

DATE=date +'%m/%d/%Y %H:%M:%S.%N' DATE=$ DATE="$DATE $HOSTNAME" 

This is because date offers seconds, nanoseconds, and nothing in between!

echo $(date '+%Y %b %d %H:%M') Your output $HOSTNAME
2013 Nov 01 09:11 Your output PEGASUS-SYDNEY-CL2

it is also possible to use backtiks caracters for this:

or with (localised) date formating:

As a complement: percentage character is not used to reference variables on any Linux shell. You should use the dollar sign for this.

You should probably read an introduction to Bash (here)

Several people have provided answers based on date , but your question requires the short day name (although my UK Win 7 installation doesn’t provide this with the ECHO command you specified), which no one has (so far) addressed.

To get this, you will probably want to include %a in the format string:

In Linux, there is the date command. If you don’t like the default format, it can be modified. See the manpage of date

For hostname, you can use hostname command, or $HOSTNAME environment variable, if it is set.

With system name, it is more complicated. You can use uname -a, sometimes it contains the OS name. Some distributions also have lsb-release, but not all of them.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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.

Читайте также:  Idea создать ярлык linux

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)

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.

Читайте также:  Команды системного администратора linux

Источник

Write current date/time to a file using shell script

I am trying to use a shell script to write the current date and time to a file. Here is what I have so far echo «$(date)» >> //home/user/Desktop/Scripts/Date Logs/datelog.txt It will say it completed but nothing is printed to the file after it is run.

1 Answer 1

Use date >> //home/user/Desktop/Scripts/Date Logs/datelog.txt .

Like i tried in my system :-

date > /tmp/date.txt . And file contains Wed Apr 5 09:27:37 IST 2017 .

[Edit] There are difference between >>(appending to the file) and >(Create the new file)

Edit:- As suggested by chepner, you can directly redirect the o/p of date command to file using date >> /tmp/date.txt .

I got it to work for 2 tries but it was appending to new file created in the Scripts directory under the file name Date.txt, figured it was caused by the space in the Date Logs directory name, changed it still no go. Date.txt output Tue Apr 4 22:35:29 CDT 2017 Logs/datelog.txt Tue Apr 4 22:41:16 CDT 2017 Logs/datelog.txt date Logs/datelog.txt date Logs/datelog.txt datelog.txt output (AfterChangingDirectoryName) date date date date My exact code at the moment getting me the output in datelog.txt file. ‘echo ‘date’ >> //home/coblere/Desktop/Scripts/DateLogs/datelog.txt’

i see in some of the file date is coming, note you need to use the « symbol to enclose the date command. not the ». first one is called back-tick and its on the same key in mac where ~ symbol is present.

Ahhhh! I mistook that simple for the simple single quote Like so ‘date’ not date now it works like a charm! Thanks for you help!

Источник

Как работать с датой и временем в 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 знает, как с этим справиться.

Читайте также:  Mozilla firefox esr 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. Дайте нам знать ваши отзывы.

Источник

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