linux bash脚本_如何在Linux终端中显示日期和时间(并在Bash脚本中使用它)-程序员宅基地

技术标签: python  java  shell  linux  大数据  

linux bash脚本

linux bash脚本

Bash shell on Unity desktop concept
Fatmawati Achmad Zaenuri/Shutterstock.com Fatmawati Achmad Zaenuri / Shutterstock.com

The date command is found in the Bash shell, which is the default shell in most Linux distributions and even macOS. This tutorial shows you how to master date on the command line and how you can use it in shell scripts to do more than simply print the time.

date命令位于Bash Shell中,Bash Shell是大多数Linux发行版甚至macOS中的默认Shell。 本教程向您展示如何在命令行上掌握date ,以及如何在shell脚本中使用它来完成除简单地打印时间之外的其他操作。

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

运行date命令以查看此信息。 它将打印您所在时区的当前日期和时间:

date
Output of the date command

The default formatting looks a little goofy. Why isn’t the year printed after the month and day, instead of being tagged on at the end, behind the timezone? Have no fear: If it’s control over the format of the output you want, date delivers it in spades. There are more than 40 options you can pass to date to instruct it to format its output precisely as you’d like.

默认格式看起来有些愚蠢。 为什么不在月份和日期之后打印年份,而不是在时区后面的末尾加标签? 不用担心:如果它控制着您想要的输出格式,那么date会以黑桃的形式传递出来。 date ,您可以传递40多个选项,以指示它完全按照自己的意愿格式化其输出。

To use any of the options type date, a space, a plus sign +, and the option including the leading percentage sign. The %c (data and time in locale format) option causes the date and time to be printed in the normalized format associated with your locale. Your locale is set by the geographical and cultural information you provided when you installed your operating system. The locale governs such things as the currency symbol, paper sizes, timezone, and other cultural norms.

要使用任何选项,请键入date ,空格,加号+以及包含前导百分号的选项。 %c (语言环境中的数据和时间)选项使日期和时间以与您的语言环境关联的规范化格式打印。 您的语言环境由安装操作系统时提供的地理和文化信息设置。 语言环境负责管理货币符号,纸张大小,时区和其他文化规范。

date +%c
Output of the date command with c option

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

现在,年份在输出中显得更加自然。

You can pass several options to date at once. A sequence of options is called a format string. To see the name of the day (%A), the day of the month (%d) and the month name (%B), use this command:

你可以通过几个选项date一次。 选项序列称为格式字符串。 要查看日期名称( %A ),月份的日期( %d )和月份的名称( %B ),请使用以下命令:

date +%A%d%B
Output of the date command with A d B options

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"
Output of the date command with A d B option with spaces

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

您可以将文本添加到格式字符串,如下所示:

date +"Today is: %A %d %B"
Output of the data command with user added text

Scrolling up and down through the date man page looking for the option you want soon becomes tiresome. We’ve wrangled the options into groups to help you find your way around them more easily.

date 手册页上上下滚动以查找您想要的选项很快就会变得很烦。 我们将选项分组,以帮助您更轻松地找到解决方法。

显示日期和时间的选项 (Options to Display the Date and Time)

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

    %c :以您所在地区的格式(包括时区)打印日期和时间。

Output of the date command

显示日期的选项 (Options to Display the Date)

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

    %D :以mm / dd / yy格式打印日期。

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

    %F :以yyyy-mm-dd格式打印日期。

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

    %x :以您所在地区的格式打印日期。

Output of the date command with D F x options

显示日期的选项 (Options to Display the Day)

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

    %a :打印日期名称,缩写为星期一,星期二,星期三等。

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

    %A :打印日期的全名,星期一,星期二,星期三等。

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

    %u :打印星期几,其中星期一= 1,星期二= 2,星期三= 3,依此类推。

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

    %w :打印星期几,其中星期日= 0,星期一= 1,星期二= 2,等等。

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

    %d :打印月份中的日期,如果需要,用前导零(01,02…09)打印。

  • %e: Prints the day of the month, with a leading space (‘ 1’, ‘ 2’ … ‘ 9’) if required. Note the apostrophes do not print.

    %e :打印月份中的日期,并在需要时以前导空格('1','2'…'9')表示。 请注意撇号不会打印。

  • %j: Prints the day of the year, with up to two leading zeroes, if required.

    %j :打印一年中的一天,如有需要,最多打印两个前导零。

Output of the date command with a A u w d e j options

显示星期的选项 (Options to Display the Week)

  • %U: Prints the week number of year, considering Sunday as the first day of the week. For example, the third week of the year, twentieth week of the year, etc.

    %U :打印年份的周数,将星期日视为一周的第一天。 例如,一年的第三周,一年的第二十周等。

  • %V: Prints the ISO week number of the year, considering Monday as the first day of the week.

    %V :打印年份的ISO周编号,将星期一视为一周的第一天。

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

    %W :一年中的第几周,将星期一视为一周的第一天。

Output of the date command with U V W options

显示月份的选项 (Options to Display the Month)

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

    %b%h :打印缩写为Jan,Feb,Mar等的月份的名称。

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

    %B :打印月份的全名,一月,二月,三月等。

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

    %m :打印月份号,如果需要,则以0开头的01、02、03…12。

Output of the date command with b h B m options

显示年份的选项 (Options to Display the Year)

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

    %C :打印不带年份的世纪。 在2019年它将打印20。

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

    %y :将年份打印为两位数字。 在2019年它将打印19。

  • %Y: Prints the year as four digits.

    %Y :将年份打印为四位数。

Output of the date command with C y Y options

显示时间的选项 (Options to Display the Time)

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

    %T :将时间打印为HH:MM:SS。

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

    %R :使用24小时制,将小时和分钟以HH:MM的形式打印,没有秒。

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

    %r :使用12小时制和am或pm指示符,根据您的语言环境打印时间。

  • %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.

    %X :使用24小时制根据您的语言环境打印时间。 据称。 请注意,在测试期间,此选项的行为与%r完全相同,如下所示。 在为英国语言环境配置并设置为GMT的Linux机器上,它使用24小时制的时钟(没有AM或PM指示器)按预期方式打印了时间。

Output of the date command with T R r X options

显示小时的选项 (Options to Display the Hour)

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

    %H :打印小时00、01、02…23。

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

    %I :使用12小时制00、01、02…12打印小时,如果需要,则以0开头。

Output of the date command with H I options

显示分钟的选项 (Options to Display Minutes)

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

    %M :打印分钟01、02、03…59,如果需要,则以前导零开始。

Output of the date command with M options

显示秒数的选项 (Options to Display Seconds)

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

    %s :打印自1970-01-01 00:00:00( Unix纪元的开始)以来的秒数。

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

    %S :打印秒01、02、03…59,如果需要,则以前导零开头。

  • %N: Prints the Nanoseconds.

    %N :打印纳秒。

Output of the date command with s S N options

显示时区信息的选项 (Options to Display Timezone Information)

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

    %z :打印您的时区和UTC之间的时差。

  • %:z: Prints the time difference between your timezone and UTC, with a : between the hours and minutes. Note the : between the % sign and z .

    %:z :打印时区和UTC之间的时差,并在小时和分钟之间显示:。 请注意:%符号和z

  • %::z: Prints the time difference between your timezone and UTC, with a : between the hours, minutes and seconds. Note the :: between the % sign and z .

    %:: z :打印时区和UTC之间的时差,并在小时,分钟和秒之间显示:。 注意%符号和z之间的::

  • %Z: Prints the alphabetic timezone name.

    %Z :打印字母时区名称。

Output of the date command with timezone options

与格式相关的选项 (Options Related to Formatting)

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

    %p :以大写形式打印AM或PM指示符。

  • %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.

    %P :以小写形式打印am或pm指示符。 注意这两个选项的怪癖。 小写的p提供大写输出,大写的P提供小写输出。

  • %t: Prints a tab.

    %t :打印选项卡。

  • %n: Prints a new line.

    %n :打印新行。

Output of the date command with AM PM indicator and formatting options

修改其他选项的选项 (Options to Modify Other Options)

These modifiers can be inserted between the % and the option letter of other options to modify their display. For example, %-S would remove the leading zero for single-digit seconds values.

这些修饰符可以插入%和其他选项的选项字母之间,以修改其显示。 例如, %-S会除去单位秒值的前导零。

  • : 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.

    0 :为单个数字值提供前导零。

  • ^: 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).

    :如果可能,请使用与默认情况相反的选项(并非所有选项都遵循此修饰符)。

Output of the date command with formatting options

另外两个整洁的技巧 (Two More Neat Tricks)

To get the last modification time of a file, use the -r (reference) option. Note that this uses a - (hyphen) instead of a % sign, and it doesn’t require a + sign. Try this command in your home folder:

要获取文件的最后修改时间,请使用-r (引用)选项。 请注意,这使用- (连字符)代替%符号,并且不需要+符号。 在您的主文件夹中尝试以下命令:

date -r .bashrc
Output of the date command with file modification time option

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

TZ设置允许您在单个命令的持续时间内更改时区。

TZ=GMT date +%c
Output of the date command for a different timezone

在脚本中使用日期 (Using Date in Scripts)

Enabling a Bash shell script to print the time and date is trivial. Create a text file with the following content, and save it as gd.sh.

启用Bash Shell脚本来打印时间和日期很简单。 创建具有以下内容的文本文件,并将其另存为gd.sh

#!/bin/bash

TODAY=$(date +"Today is %A, %d of %B")
TIMENOW=$(date +"The 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
Output of the gd.sh script

We can use the date command to provide a timestamp. The script shown will create a directory with the timestamp as its name. It will then copy all text files from the current folder into it. By running this script periodically we can take a snapshot of our text files. Over time we’ll build up a series of folders with different versions of our text files in them.

我们可以使用date命令来提供时间戳。 显示的脚本将创建一个以时间戳为名称的目录。 然后它将所有文本文件从当前文件夹复制到其中。 通过定期运行此脚本,我们可以拍摄文本文件的快照。 随着时间的流逝,我们将建立一系列包含不同版本文本文件的文件夹。

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.

创建具有以下内容的文本文件,并将其另存为snapshot.sh.

#!/bin/bash

# obtain the date and time
date_stamp=$(date +"%F-%H-%M-%S")

# make a directory with that name
mkdir "$date_stamp"

# copy the files from the current folder into it
cp *.txt "$date_stamp"

# all done, report back and exit
echo "Text files copied to directory: "$date_stamp

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

键入以下命令来设置执行权限并使脚本可执行。

chmod +x snapshot.sh

Run the script with this command:

使用以下命令运行脚本:

./snapshot.sh
Effect of running the snapshot.sh script

You’ll see that a directory has been created. Its name is the date and time at which the script was executed. Inside that directory are copies of the text files.

您会看到目录已创建。 它的名称是执行脚本的日期和时间。 在该目录内是文本文件的副本。

Given a bit of thought and creativity, even the humble date command can be put to productive use.

给定一个位的思想和创意,甚至不起眼的date命令可以投入生产使用。

翻译自: https://www.howtogeek.com/410442/how-to-display-the-date-and-time-in-the-linux-terminal-and-use-it-in-bash-scripts/

linux bash脚本

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/culiuman3228/article/details/108787905

智能推荐

线上PHP问题排查思路与实践-程序员宅基地

文章浏览阅读210次。转载:http://www.bo56.com/%E7%BA%BF%E4%B8%8Aphp%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5%E6%80%9D%E8%B7%AF%E4%B8%8E%E5%AE%9E%E8%B7%B5/前几天,在一淘网,腾讯网媒和微博商业技术联合组织的技术分享大会上,我分享了《在线PHP问题排查思路与实践》。此博文除了对PPT..._在php开发过程中,线上代码怎么查哪段代码有问题,且不影响线上运行

linux 内核升级-程序员宅基地

文章浏览阅读841次,点赞28次,收藏9次。centos 7.x 升级内核 3.x 至 5.x

去掉java文件中的注释_利用JavaParser去除java文件中的注释-程序员宅基地

文章浏览阅读922次。利用JavaParser去除java文件中的注释个人博客:记录一下在项目实施过程中的一些点情景回顾之前项目有个需求,就是去掉.java文件中的所有注释,常用的方法是用正则匹配。然而在网络上查找到的正则或多或少都有一些问题,无法匹配到所有的情况。或者说,由于写.java文件的人的不规范(各种奇葩的问题),导致正则覆盖不全。所以正则方法不靠谱,或者说,存在一定的限制。新的想法后来想到利用AST来去除注..._在线java代码去除注释工具

VSCode - 使用VSCode远程连接到Linux并实现免密码登录_vscode连接linux-程序员宅基地

文章浏览阅读3w次,点赞77次,收藏282次。VSCode - Linux - 使用VSCode远程连接到Ubuntu并实现免密登录我使用的是Ubuntu14.04,即便是使用其他发行版也不会影响操作步骤_vscode连接linux

生活随记-腊月第一天-程序员宅基地

文章浏览阅读2.3k次。年底了总是很容易思考人生。出差坐在太原的yd酒店15楼,泡一壶茶翻着书听点音乐,坐在窗边看下空旷冷清的街道。感叹一声,逝者如斯夫不舍昼夜。这一年年过得真快。思考着自己的工作和以后的生活,何去何从。很多事情形成习惯之后就会懒得去改变,逐渐形成一种倦怠。工作,生活,投资也是。也好,今晚就让自己沉浸在无尽交织的思绪中吧。明天睡个懒觉吃个brunch回上海。转眼又到12月了。..._腊月第一天

ftp 下载时防止从缓存中获取文件-程序员宅基地

文章浏览阅读1k次。//http://baike.baidu.com/link?url=QucJiA_Fg_-rJI9D4G4Z4687HG4CfhtmBUd5TlXrcWCeIEXCZxIh0TD7ng1wROAzAuGD8qncM65XK4BZ1K1uqqintCFTP_MFC_TESTDlg::FTP_DownLoadFile(char*FtpIp,char*User,char*Passwor..._ftp 不使用缓存

随便推点

深信服AF防火墙配置SSL VPN_深信服ssl配置教程-程序员宅基地

文章浏览阅读1.5k次,点赞6次,收藏13次。深信服防火墙配置SSL VN_深信服ssl配置教程

linux系统rabbitmq安装步骤_rabbitmq linux安装-程序员宅基地

文章浏览阅读768次。一、安装erlang:1、先下载rpm包:wget https://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm2、rpm包:rpm -Uvh erlang-solutions-1.0-1.noarch.rpm可能会有以下问题:解决办法:(执行以下命令后,在执行上一条命令)yum..._rabbitmq linux安装

CentOS 7 安装最新版Docker教程_centos7安装最新版dockers-程序员宅基地

文章浏览阅读781次。docker安装官方文档:Install Docker Engine on CentOS2、安装提供了工具3、通过添加docker repository如果出现上面的错误提示,可通阿里源进行添加4、安装docker4.1、直接安装最新版本这步完成后可直接跳至启动docker4.2、或者安装指定版本按版本号倒序列出可安装版本列表安装指定版本例如安装20.10.9版本5、启动docker通过进行启动设置docker服务开机启动6、测试7、卸载docker下的_centos7安装最新版dockers

敏感字识别算法基于JDK8 lambada表达式_敏感文本识别算法-程序员宅基地

文章浏览阅读429次。package aaa.bbb.demo;import java.util.ArrayList;import java.util.List;public class RecognitionDemo { public static void main(String[] args) { String str1="SB哈NM哈哈哈WBDhdsada"; String str_敏感文本识别算法

华为鸿蒙系统(Huawei HarmonyOS)

华为鸿蒙系统Huawei HarmonyOS

JS读取粘贴板内容-程序员宅基地

文章浏览阅读4.9k次。1.1 监听onpaste事件1.1.1 定义和用法npaste 事件在用户向元素中粘贴文本时触发。注意:虽然使用的 HTML 元素都支持 onpaste 事件,但实际上并非支持所有元素,例如 <p> 元素, 除非设置了 contenteditable 为 "true" (查看下文的更多实例)。提示:onpaste 事件通常用于 type="text" 的 ..._js 获取粘贴板内容 移动端