简体   繁体   English

Mac OS 终端脚本文件变量 (.command)

[英]Mac OS terminal script file variables (.command)

I'm fairly new to writing scripts on Mac OS so apologies if the answer is fairly obvious.我对在 Mac OS 上编写脚本还很陌生,所以如果答案很明显,我很抱歉。

I want to add a date variable to my script on Mac OS that will output the current date in YYYYMMDD format.我想在 Mac OS 上的脚本中添加一个日期变量,它将 output 为 YYYYMMDD 格式的当前日期。

On Windows I would write this as:在 Windows 我会这样写:

set now=%date:~6,4%%date:~3,2%%date:~0,2%
%now%

How would I do something similar when writing a.command file on Mac OS?在 Mac OS 上编写 a.command 文件时,我将如何做类似的事情?

You can run this in a terminal/bash script您可以在终端/bash 脚本中运行它

myDate=$(date +%F) 
echo $myDate

It outputs a date like:它输出一个日期,如:

2021-05-21

Alternatively you can specify a formatter:或者,您可以指定格式化程序:

myDate=$(date +%Y%m%d) # to remove the dashes

Starting in bash 4.1 or 4.2, the builtin printf can emit the formatted time:从 bash 4.1 或 4.2 开始,内置printf可以发出格式化时间:

printf '%(%Y%m%d)T' -1      # => 20210521

Since MacOS ships with bash 3.2 by default that means you'll need to install a newer version yourself.由于 MacOS 默认附带 bash 3.2,这意味着您需要自己安装更新的版本。 With Homebrew that is as easy as brew install bash使用Homebrew就像brew install bash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM