shell unix 中的 Concat 变量(日期)和字符串 - bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37563704/
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
Concat Variable (date) and String in shell unix - bash
提问by Tizianoreica
I'm trying to concat a var (date) and string to have a file with current date name.
我正在尝试连接一个 var(日期)和字符串以获得一个具有当前日期名称的文件。
My code.
我的代码。
days="$(date +"%Y%m%d_%H%M")"
echo "SKIP" > ${days}_EMERGENCY.txt
but when I run, I get a file with a ? in file name, like this:
但是当我运行时,我得到一个带有 ? 在文件名中,像这样:
Am I doing something wrong?
难道我做错了什么?
EDIT
编辑
Looking at symbol, ? stands for \r - could it be because I'm writing on notepad and then upload via ftp the .sh script?
看着符号, ? 代表\r - 可能是因为我在记事本上写,然后通过 ftp 上传 .sh 脚本?
EDIT 2
编辑 2
回答by Stefan Hegny
I guess your vi will have made the entire file DOS-style and so there will be another carriage return at the end of the echo statement
我猜你的 vi 会把整个文件做成 DOS 风格,所以在 echo 语句的末尾会有另一个回车
Try dos2unix or using an editor that allows you to change the line-ending style or
尝试 dos2unix 或使用允许您更改行尾样式的编辑器或
sed -i "s/$( printf '5' )//g" yourscript
回答by Dilettant
It works on my system (OS X) even with double quotes everywhere. For variation I used:
它适用于我的系统(OS X),即使到处都是双引号。对于我使用的变化:
$> days="$(date +'%Y%m%d_%H%M')"
$> echo $days
20160601_1051
$> echo "SKIP" > ${days}_EMERGENCY.txt
$> ll ${days}_EMERGENCY.txt
-rw-r--r-- 1 user team 5 Jun 1 10:52 20160601_1051_EMERGENCY.txt
回答by alijandro
try to remove the redundant double quote in your first variable assignment.
尝试在您的第一个变量赋值中删除多余的双引号。
$ days=$(date +%Y%m%d_%H%M)
$ echo $days #see what output will get?
$ echo "SKIP" > ${days}_EMERGENCY.txt