使用参数变量在 bash 脚本中获取 X 天前的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18060210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting date of X days ago in bash script, using argument variable
提问by Kof
I'm trying to calculate the date for a dynamic number of days ago in a bash script.
我正在尝试在 bash 脚本中计算动态天数前的日期。
This is what I've done -
这就是我所做的-
#!/bin/bash
STAMP=`date --date=' day ago' +%y%m%d`
but when running myscript 2
, it says -
但是在运行时myscript 2
,它说-
date: invalid date ` day ago'
How can I use my argument value in this formula?
我如何在这个公式中使用我的参数值?
回答by Kof
It works if ' is replaced with " into this command on the script -
如果在脚本中将 ' 替换为 " 到此命令中,它会起作用 -
STAMP=`date --date=" day ago" +%y%m%d`
The clue was the two different character ` and ' used in the error response -
线索是错误响应中使用的两个不同字符 ` 和 ' -
date: invalid date ` day ago'
An expert in bash scripting (not me) can probably explain why this has happen.
bash 脚本专家(不是我)可能会解释为什么会发生这种情况。
回答by devnull
It's because variable substitution wouldn't happen in single quotes, i.e. '$1'
wouldn't expand but "$1"
would.
这是因为变量替换不会发生在单引号中,即'$1'
不会扩展但"$1"
会。
As such, saying
如此,说
STAMP=`date --date=" day ago" +%y%m%d`
or
或者
STAMP=$(date --date=" day ago" +%y%m%d)
would work.
会工作。