Linux shell 脚本:使用当前日期名称创建一个文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13731463/
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
Linux shell script : make a folder with the current date name
提问by SteveL
I am trying to make a simple backup script and i have problem creating a folder with the curent date for name
我正在尝试制作一个简单的备份脚本,但我在创建一个名称为当前日期的文件夹时遇到问题
My script is that and basically the problem is on the last line
我的脚本就是这样,基本上问题出在最后一行
drivers=$(ls /media/)
declare -i c=0
for word in $drivers
do
echo "($c)$word"
c=c+1
done
read -n 1 drive
echo
c=0
for word in $drivers
do
if [ $c -eq $drive ]
then
backuppath="/media/$word/backup"
fi
c=c+1
done
echo "doing back up to $backuppath"
cp -r /home/stefanos/Programming $backuppath/$(date +%Y-%m-%d-%T)
Ouput:
输出:
(0)0362-BA96
(1)Data
(2)Windows
0
doing back up to /media/0362-BA96/backup
cp: cannot create directory `/media/0362-BA96/backup/2012-12-05-21:58:37': Invalid argument
The path is triply checked that is existing until /media/0362-BA96/
路径经过三次检查,直到 /media/0362-BA96/
SOLVED: Did what janisz said the final script looks like
已解决:按照 janisz 所说的,最终脚本看起来像
drivers=$(ls /media/)
declare -i c=0
for word in $drivers
do
echo "($c)$word"
c=c+1
done
read -n 1 drive
echo
c=0
for word in $drivers
do
if [ $c -eq $drive ]
then
backuppath="/media/$word/backup"
fi
c=c+1
done
echo "doing back up to $backuppath"
backup(){
time_stamp=$(date +%Y_%m_%d_%H_%M_%S)
mkdir -p "${backuppath}/${time_stamp}"
cp -r "" "${backuppath}/${time_stamp}"
echo "backup complete in "
}
#####################The paths to backup####################
backup "/home/stefanos/Programming"
backup "/home/stefanos/Android/Projects"
backup "/home/stefanos/Dropbox"
采纳答案by janisz
:
is not valid on FAT (it is used to specify disk). Some of M$ invalid character works on GNU/Linux systems but it is safer to avoid them (just replace with .
). Use following date format
:
在 FAT 上无效(用于指定磁盘)。一些 M$ 无效字符适用于 GNU/Linux 系统,但避免它们更安全(只需替换为.
)。使用以下日期格式
date +%Y_%m_%d_%H_%M_%S
It should works on most file systems but it could be too long for MS DOS FAT. More info you will find here.
它应该适用于大多数文件系统,但对于 MS DOS FAT 来说可能太长了。您将在此处找到更多信息。
回答by sampson-chen
Trying changing it to:
尝试将其更改为:
time_stamp=$(date +%Y-%m-%d-%T)
mkdir -p "${backuppath}/${time_stamp}"
cp -r /home/stefanos/Programming "${backuppath}/${time_stamp}"