Bash, find and delete old files2019 Community Moderator ElectionBash script for scp interpreting tilde (~) too soonFind and delete duplicate txt filesI'm copying if-then statements, with slight variations… and I shouldn't have toDelete files that are not part of a bash arrayOld file deletion scriptBackup using find and ssh to off-site serverBash script unable to move filesReplacing a running binary on read-only file systemweb-based backup strategy implementation for Ubuntu linuxQuestions about Rsnapshot - user permissions, deletion and hardlinks

Is there a distance limit for minecart tracks?

Does capillary rise violate hydrostatic paradox?

Exposing a company lying about themselves in a tightly knit industry (videogames) : Is my career at risk on the long run?

What (if any) is the reason to buy in small local stores?

Did I make a mistake by ccing email to boss to others?

Connection Between Knot Theory and Number Theory

What is the tangent at a sharp point on a curve?

Mortal danger in mid-grade literature

Make a Bowl of Alphabet Soup

How can a new country break out from a developed country without war?

New Order #2: Turn My Way

A seasonal riddle

Showing mass murder in a kid's book

Why do Radio Buttons not fill the entire outer circle?

Highest stage count that are used one right after the other?

Trouble reading roman numeral notation with flats

Why can't I get pgrep output right to variable on bash script?

Relations between homogeneous polynomials

Do people actually use the word "kaputt" in conversation?

Why doesn't Gödel's incompleteness theorem apply to false statements?

Amorphous proper classes in MK

Hashing password to increase entropy

Why does a 97 / 92 key piano exist by Bosendorfer?

Unfrosted light bulb



Bash, find and delete old files



2019 Community Moderator ElectionBash script for scp interpreting tilde (~) too soonFind and delete duplicate txt filesI'm copying if-then statements, with slight variations… and I shouldn't have toDelete files that are not part of a bash arrayOld file deletion scriptBackup using find and ssh to off-site serverBash script unable to move filesReplacing a running binary on read-only file systemweb-based backup strategy implementation for Ubuntu linuxQuestions about Rsnapshot - user permissions, deletion and hardlinks










1















Write script to backup files and delete old backups:



#!/bin/sh

BACKUPDIR=/var/backups/files
ROTATE=1

mkdir -p $BACKUPDIR

CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

cd /var/ && tar czf $CURRENT www

find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;

chmod 0600 $BACKUPDIR/*


Command Line (for testing):



find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;


Somehow, the script does not work. However, if I execute it in the console, all is OK and old files get deleted. But if I run the script, files are not deleted (tar archive get created when I run the script). Why?



Script permissions are 755.










share|improve this question
















bumped to the homepage by Community 15 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • If you want to delete files more than 24hrs old, you should specify -mtime +0 for find. -mtime 1 means files 24hrs to 48hrs old.

    – yaegashi
    Jul 27 '15 at 6:30






  • 1





    -mtime 1 mean exactly 1 day old from now, so may be there are not such files in your $BACKUPDIR

    – Costas
    Jul 27 '15 at 7:51






  • 1





    rather than -exec rm , you might want to use the -delete option.

    – Fiximan
    Jul 27 '15 at 8:39















1















Write script to backup files and delete old backups:



#!/bin/sh

BACKUPDIR=/var/backups/files
ROTATE=1

mkdir -p $BACKUPDIR

CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

cd /var/ && tar czf $CURRENT www

find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;

chmod 0600 $BACKUPDIR/*


Command Line (for testing):



find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;


Somehow, the script does not work. However, if I execute it in the console, all is OK and old files get deleted. But if I run the script, files are not deleted (tar archive get created when I run the script). Why?



Script permissions are 755.










share|improve this question
















bumped to the homepage by Community 15 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • If you want to delete files more than 24hrs old, you should specify -mtime +0 for find. -mtime 1 means files 24hrs to 48hrs old.

    – yaegashi
    Jul 27 '15 at 6:30






  • 1





    -mtime 1 mean exactly 1 day old from now, so may be there are not such files in your $BACKUPDIR

    – Costas
    Jul 27 '15 at 7:51






  • 1





    rather than -exec rm , you might want to use the -delete option.

    – Fiximan
    Jul 27 '15 at 8:39













1












1








1


1






Write script to backup files and delete old backups:



#!/bin/sh

BACKUPDIR=/var/backups/files
ROTATE=1

mkdir -p $BACKUPDIR

CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

cd /var/ && tar czf $CURRENT www

find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;

chmod 0600 $BACKUPDIR/*


Command Line (for testing):



find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;


Somehow, the script does not work. However, if I execute it in the console, all is OK and old files get deleted. But if I run the script, files are not deleted (tar archive get created when I run the script). Why?



Script permissions are 755.










share|improve this question
















Write script to backup files and delete old backups:



#!/bin/sh

BACKUPDIR=/var/backups/files
ROTATE=1

mkdir -p $BACKUPDIR

CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

cd /var/ && tar czf $CURRENT www

find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;

chmod 0600 $BACKUPDIR/*


Command Line (for testing):



find $BACKUPDIR -type f -mtime $ROTATE -exec rm ;


Somehow, the script does not work. However, if I execute it in the console, all is OK and old files get deleted. But if I run the script, files are not deleted (tar archive get created when I run the script). Why?



Script permissions are 755.







bash scripting backup






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 25 '16 at 21:47









Julie Pelletier

6,98211340




6,98211340










asked Jul 27 '15 at 5:00









FoxDevFoxDev

1061




1061





bumped to the homepage by Community 15 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 15 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • If you want to delete files more than 24hrs old, you should specify -mtime +0 for find. -mtime 1 means files 24hrs to 48hrs old.

    – yaegashi
    Jul 27 '15 at 6:30






  • 1





    -mtime 1 mean exactly 1 day old from now, so may be there are not such files in your $BACKUPDIR

    – Costas
    Jul 27 '15 at 7:51






  • 1





    rather than -exec rm , you might want to use the -delete option.

    – Fiximan
    Jul 27 '15 at 8:39

















  • If you want to delete files more than 24hrs old, you should specify -mtime +0 for find. -mtime 1 means files 24hrs to 48hrs old.

    – yaegashi
    Jul 27 '15 at 6:30






  • 1





    -mtime 1 mean exactly 1 day old from now, so may be there are not such files in your $BACKUPDIR

    – Costas
    Jul 27 '15 at 7:51






  • 1





    rather than -exec rm , you might want to use the -delete option.

    – Fiximan
    Jul 27 '15 at 8:39
















If you want to delete files more than 24hrs old, you should specify -mtime +0 for find. -mtime 1 means files 24hrs to 48hrs old.

– yaegashi
Jul 27 '15 at 6:30





If you want to delete files more than 24hrs old, you should specify -mtime +0 for find. -mtime 1 means files 24hrs to 48hrs old.

– yaegashi
Jul 27 '15 at 6:30




1




1





-mtime 1 mean exactly 1 day old from now, so may be there are not such files in your $BACKUPDIR

– Costas
Jul 27 '15 at 7:51





-mtime 1 mean exactly 1 day old from now, so may be there are not such files in your $BACKUPDIR

– Costas
Jul 27 '15 at 7:51




1




1





rather than -exec rm , you might want to use the -delete option.

– Fiximan
Jul 27 '15 at 8:39





rather than -exec rm , you might want to use the -delete option.

– Fiximan
Jul 27 '15 at 8:39










1 Answer
1






active

oldest

votes


















0














As suggested by Fiximan, you probably want to use the -delete option, although that should make no difference in your situation, if you were to hit a filename with spaces or other special characters, your script would fail.



#!/bin/sh -e

BACKUPDIR=/var/backups/files

# I suggest a little more than 1 day (i.e. about 1 week of backups is
# probably safer.)
ROTATE=7

mkdir -p $BACKUPDIR

CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

# Create protected file, then backup data in it
touch $CURRENT
chmod 600 $CURRENT
cd /var/ && tar czf $CURRENT www

# Here we have the attempt at deleting, notice the "+"
find $BACKUPDIR -type f -name '*-files.tar.gz' -mtime +$ROTATE -delete


A few things:



  1. ROTATE=1 does not seem to make much sense, you probably want more than 1 backup, just in case. You often notice something's wrong a few days in... good luck if you have a backup from last night only!


  2. chmod 600 $CURRENT should be done as soon as possible; if you are really afraid for the security of the file, do it before creating the tarball (as shown in my sample.)


  3. Fix the find by adding a + in front of the $ROTATE number. This is something that gets me each time, so don't feel bad. Actually, if you use + it has the mean of older or equal, and if you use '-', the test is inverted (so -mtime +7 is more or less equivalent to ! -mtime -7 — probably within 1 day in between which is not unlikely to match one side or the other.) With a plain number as you used (-mtime 1), it will delete files that were modified on that particular day. If that script does not run for 3 days, then those 3 files won't ever get deleted.


  4. Use the -delete so you do not have to think about the quotations you missed in your sample code (i.e. -exec rm "" ;) in case the filename includes special characters.


  5. I suggest you add a -name because you have a simple way to know whether the file in question is a backup. This is just for security. If you never ever put any other file in that directory (like a copy of a backup you want to keep for a longer period of time) then you do not need it.


  6. Adding the -e option in the hash bang (#!/bin/sh -e) is a good idea so the script stops on the very first error. At times scripts run, generate errors, and you never see them.






share|improve this answer






















    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "106"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f218545%2fbash-find-and-delete-old-files%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    As suggested by Fiximan, you probably want to use the -delete option, although that should make no difference in your situation, if you were to hit a filename with spaces or other special characters, your script would fail.



    #!/bin/sh -e

    BACKUPDIR=/var/backups/files

    # I suggest a little more than 1 day (i.e. about 1 week of backups is
    # probably safer.)
    ROTATE=7

    mkdir -p $BACKUPDIR

    CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

    # Create protected file, then backup data in it
    touch $CURRENT
    chmod 600 $CURRENT
    cd /var/ && tar czf $CURRENT www

    # Here we have the attempt at deleting, notice the "+"
    find $BACKUPDIR -type f -name '*-files.tar.gz' -mtime +$ROTATE -delete


    A few things:



    1. ROTATE=1 does not seem to make much sense, you probably want more than 1 backup, just in case. You often notice something's wrong a few days in... good luck if you have a backup from last night only!


    2. chmod 600 $CURRENT should be done as soon as possible; if you are really afraid for the security of the file, do it before creating the tarball (as shown in my sample.)


    3. Fix the find by adding a + in front of the $ROTATE number. This is something that gets me each time, so don't feel bad. Actually, if you use + it has the mean of older or equal, and if you use '-', the test is inverted (so -mtime +7 is more or less equivalent to ! -mtime -7 — probably within 1 day in between which is not unlikely to match one side or the other.) With a plain number as you used (-mtime 1), it will delete files that were modified on that particular day. If that script does not run for 3 days, then those 3 files won't ever get deleted.


    4. Use the -delete so you do not have to think about the quotations you missed in your sample code (i.e. -exec rm "" ;) in case the filename includes special characters.


    5. I suggest you add a -name because you have a simple way to know whether the file in question is a backup. This is just for security. If you never ever put any other file in that directory (like a copy of a backup you want to keep for a longer period of time) then you do not need it.


    6. Adding the -e option in the hash bang (#!/bin/sh -e) is a good idea so the script stops on the very first error. At times scripts run, generate errors, and you never see them.






    share|improve this answer



























      0














      As suggested by Fiximan, you probably want to use the -delete option, although that should make no difference in your situation, if you were to hit a filename with spaces or other special characters, your script would fail.



      #!/bin/sh -e

      BACKUPDIR=/var/backups/files

      # I suggest a little more than 1 day (i.e. about 1 week of backups is
      # probably safer.)
      ROTATE=7

      mkdir -p $BACKUPDIR

      CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

      # Create protected file, then backup data in it
      touch $CURRENT
      chmod 600 $CURRENT
      cd /var/ && tar czf $CURRENT www

      # Here we have the attempt at deleting, notice the "+"
      find $BACKUPDIR -type f -name '*-files.tar.gz' -mtime +$ROTATE -delete


      A few things:



      1. ROTATE=1 does not seem to make much sense, you probably want more than 1 backup, just in case. You often notice something's wrong a few days in... good luck if you have a backup from last night only!


      2. chmod 600 $CURRENT should be done as soon as possible; if you are really afraid for the security of the file, do it before creating the tarball (as shown in my sample.)


      3. Fix the find by adding a + in front of the $ROTATE number. This is something that gets me each time, so don't feel bad. Actually, if you use + it has the mean of older or equal, and if you use '-', the test is inverted (so -mtime +7 is more or less equivalent to ! -mtime -7 — probably within 1 day in between which is not unlikely to match one side or the other.) With a plain number as you used (-mtime 1), it will delete files that were modified on that particular day. If that script does not run for 3 days, then those 3 files won't ever get deleted.


      4. Use the -delete so you do not have to think about the quotations you missed in your sample code (i.e. -exec rm "" ;) in case the filename includes special characters.


      5. I suggest you add a -name because you have a simple way to know whether the file in question is a backup. This is just for security. If you never ever put any other file in that directory (like a copy of a backup you want to keep for a longer period of time) then you do not need it.


      6. Adding the -e option in the hash bang (#!/bin/sh -e) is a good idea so the script stops on the very first error. At times scripts run, generate errors, and you never see them.






      share|improve this answer

























        0












        0








        0







        As suggested by Fiximan, you probably want to use the -delete option, although that should make no difference in your situation, if you were to hit a filename with spaces or other special characters, your script would fail.



        #!/bin/sh -e

        BACKUPDIR=/var/backups/files

        # I suggest a little more than 1 day (i.e. about 1 week of backups is
        # probably safer.)
        ROTATE=7

        mkdir -p $BACKUPDIR

        CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

        # Create protected file, then backup data in it
        touch $CURRENT
        chmod 600 $CURRENT
        cd /var/ && tar czf $CURRENT www

        # Here we have the attempt at deleting, notice the "+"
        find $BACKUPDIR -type f -name '*-files.tar.gz' -mtime +$ROTATE -delete


        A few things:



        1. ROTATE=1 does not seem to make much sense, you probably want more than 1 backup, just in case. You often notice something's wrong a few days in... good luck if you have a backup from last night only!


        2. chmod 600 $CURRENT should be done as soon as possible; if you are really afraid for the security of the file, do it before creating the tarball (as shown in my sample.)


        3. Fix the find by adding a + in front of the $ROTATE number. This is something that gets me each time, so don't feel bad. Actually, if you use + it has the mean of older or equal, and if you use '-', the test is inverted (so -mtime +7 is more or less equivalent to ! -mtime -7 — probably within 1 day in between which is not unlikely to match one side or the other.) With a plain number as you used (-mtime 1), it will delete files that were modified on that particular day. If that script does not run for 3 days, then those 3 files won't ever get deleted.


        4. Use the -delete so you do not have to think about the quotations you missed in your sample code (i.e. -exec rm "" ;) in case the filename includes special characters.


        5. I suggest you add a -name because you have a simple way to know whether the file in question is a backup. This is just for security. If you never ever put any other file in that directory (like a copy of a backup you want to keep for a longer period of time) then you do not need it.


        6. Adding the -e option in the hash bang (#!/bin/sh -e) is a good idea so the script stops on the very first error. At times scripts run, generate errors, and you never see them.






        share|improve this answer













        As suggested by Fiximan, you probably want to use the -delete option, although that should make no difference in your situation, if you were to hit a filename with spaces or other special characters, your script would fail.



        #!/bin/sh -e

        BACKUPDIR=/var/backups/files

        # I suggest a little more than 1 day (i.e. about 1 week of backups is
        # probably safer.)
        ROTATE=7

        mkdir -p $BACKUPDIR

        CURRENT="$BACKUPDIR/`date +%Y-%m-%d`-files.tar.gz"

        # Create protected file, then backup data in it
        touch $CURRENT
        chmod 600 $CURRENT
        cd /var/ && tar czf $CURRENT www

        # Here we have the attempt at deleting, notice the "+"
        find $BACKUPDIR -type f -name '*-files.tar.gz' -mtime +$ROTATE -delete


        A few things:



        1. ROTATE=1 does not seem to make much sense, you probably want more than 1 backup, just in case. You often notice something's wrong a few days in... good luck if you have a backup from last night only!


        2. chmod 600 $CURRENT should be done as soon as possible; if you are really afraid for the security of the file, do it before creating the tarball (as shown in my sample.)


        3. Fix the find by adding a + in front of the $ROTATE number. This is something that gets me each time, so don't feel bad. Actually, if you use + it has the mean of older or equal, and if you use '-', the test is inverted (so -mtime +7 is more or less equivalent to ! -mtime -7 — probably within 1 day in between which is not unlikely to match one side or the other.) With a plain number as you used (-mtime 1), it will delete files that were modified on that particular day. If that script does not run for 3 days, then those 3 files won't ever get deleted.


        4. Use the -delete so you do not have to think about the quotations you missed in your sample code (i.e. -exec rm "" ;) in case the filename includes special characters.


        5. I suggest you add a -name because you have a simple way to know whether the file in question is a backup. This is just for security. If you never ever put any other file in that directory (like a copy of a backup you want to keep for a longer period of time) then you do not need it.


        6. Adding the -e option in the hash bang (#!/bin/sh -e) is a good idea so the script stops on the very first error. At times scripts run, generate errors, and you never see them.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 25 '16 at 21:42









        Alexis WilkeAlexis Wilke

        1,044718




        1,044718



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f218545%2fbash-find-and-delete-old-files%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

            Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

            Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.