How to back up all files inside directory (all tree folders and files) to archive and then send to ftp server? Can I do this using cronjobs? How should tar command look like to back up /home/user/ directory and all files and folders inside to /home/ with compression?
cd /my/very/interesting/and/important/directory & tar -cjf . backup.tar.bz2 –exclude & backup.tar.bz2 & sftp backup.tar.bz2 me@myserver
as far as i understand is equal to:
- cd /my/very/interesting/and/important/directory
- tar -cjf . backup.tar.bz2 –exclude
- backup.tar.bz2
-
sftp backup.tar.bz2 me@myserver
- what parameter
jmeans in 2nd command? - probably there should not be a
&betweentar -cjf . backup.tar.bz2 --excludeANDbackup.tar.bz2. Because&merges commands. Right? - what about password param in 4th command?
- what parameter
A cron job issues a command. If you can do it from the command line, you can to it with cron.
There are at least three simple ways to accomplish what you want:
&&. However, I don’t recommend this, see below.This is an example series of skeleton commands that might be useful. This is more intended as a sketch of the concept rather than a comprehensive, working script. For instance, I’m not sure how to use
sftpwithout having to manually enter a password, so I left that out. Look up the documentation for the commands used and figure out yourself what to use and how in your specific case, maybe you’ll even learn something along the way. 😉You could put the above commands in a shell script, or combine them into one command, like so:
This, however, is horribly ugly if you ask me. I’d go with the shell or ant script options to improve readability and avoid maintenance headaches. Those methods also make it easier to maintain in another way: you don’t have to update the crontab every time you need to make a change to the backup script, just edit the script and you’re good to go.
The
&&operatorSeparating two commands with
&&tells bash to run the second command if and only if the first command exits with status0, which is the standard exit code used when commands exit successfully. This may be compared to;, which can be used to run multiple commands in succession regardless of success or failure. Using&&means that the series of commands stops if something goes wrong along the way. For instance, iftarfails to create an archive, there’s no use in attempting to compress that archive afterwards.What really happens behind the scenes is short-circuit logic.
cmd1 && cmd2is a logic statement that says “Returntrueif bothcmd1andcmd2exit with exit code0, otherwise returnfalse” (thoughtrueandfalseare actually represented by numbers). Ifcmd1doesn’t exit with exit code0, then the logic statement is alreadyfalse, and the statement returnsfalsewithout runningcmd2.