简体   繁体   中英

Linux shell script : make a folder with the current date name

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/

SOLVED : Did what janisz said the final script looks like

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"

Trying changing it to:

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

: 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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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