Linux shell脚本:创建一个包含当前日期名称的文件夹

时间:2012-12-05 20:04:02

标签: linux bash shell

我正在尝试创建一个简单的备份脚本,但我在创建名称为curent date的文件夹时遇到问题

我的脚本就是这样,基本上问题出在最后一行

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)

输出继电器:

(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

在/ media / 0362-BA96 /

之前检查路径是否存在

解决:     是什么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}$1"
  cp -r "${1}" "${backuppath}/${time_stamp}$1"

  echo "backup complete in $1"
}

#####################The paths to backup####################

backup "/home/stefanos/Programming"
backup "/home/stefanos/Android/Projects"
backup "/home/stefanos/Dropbox"

2 个答案:

答案 0 :(得分:17)

尝试将其更改为:

time_stamp=$(date +%Y-%m-%d-%T)
mkdir -p "${backuppath}/${time_stamp}"
cp -r /home/stefanos/Programming "${backuppath}/${time_stamp}"

答案 1 :(得分:13)

:在FAT上无效(用于指定磁盘)。一些M $无效字符适用于GNU / Linux系统,但避免它们更安全(只需用.替换)。使用以下日期格式

date +%Y_%m_%d_%H_%M_%S

它应该适用于大多数文件系统,但对于MS DOS FAT来说可能太长了。更多信息,你会发现here