Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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"
like image 906
SteveL Avatar asked Dec 05 '12 20:12

SteveL


People also ask

How do I create a folder for today's date?

For a Windows batch-file, you'd just use mkdir "%DATE%" or mkdir "%datestamp%" -- whichever variable you want to use.

How do I print the current date in Shell?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...


1 Answers

Trying changing it to:

time_stamp=$(date +%Y-%m-%d-%T)
mkdir -p "${backuppath}/${time_stamp}"
cp -r /home/stefanos/Programming "${backuppath}/${time_stamp}"
like image 91
sampson-chen Avatar answered Oct 11 '22 16:10

sampson-chen