Overwrite an existing directory?
Solution 1:
If your goal is to execute a one-line command that:
- Removes and recreates the directory
~/Desktop/foo
if it already exists. - Just creates the directory
~/Desktop/foo
if it does not already exist.
Then you can use:
rm -r ~/Desktop/foo; mkdir ~/Desktop/foo
;
is equivalent to a newline, but it lets you execute multiple commands on a single line (i.e., as a "single command").
- If the directory you're removing may contain readonly files, you'll need the
-f
flag to remove them without prompting the user interactively. This is okay, but I do recommend being especially careful withrm -rf ...
. Seeman rm
for details. - You need the
rm
command to finish before themkdir
command executes; this is the reason to use;
instead of&
. (A command preceding&
runs asynchronously in the background.) - You need the
mkdir
command to run when therm
command succeeds; this is the reason to use;
instead of||
. - You need the
mkdir
command to run when therm
command fails (usually failure will mean the directory didn't already exist); this is the reason to use;
instead of&&
. - The
rm
command might fail even when the directory already existed, in which case themkdir
command will fail also, but the error messages will make sense and there's probably no need to add a middle step checking forfoo
's existence before trying to create it.
See 3.2.3 Lists of Commands in the Bash Reference Manual for more information and explanation about the ;
, &
, ||
, and &&
operators.
As muru suggested (and Rinzwind elaborated), I do recommend you look into rsync
to see if it will meet your backup needs. There are some additional useful guides on the rsync documentation page, as well as this Ubuntu rsync guide.
why mkdir doesn't has this option ?
mkdir
creates directories (the "mk" stands for "make"). For it also to recursively delete directories and all the files in them would be bad, because it would violate the principle of least astonishment in a way that would likely lead to data loss.
rmdir
doesn't even remove directories that have any (non-directory) files in them. rm
has an -r
option, which makes sense since rm
is expected to remove files (that is its purpose, thus the inherent danger is intuitive and users typically know to be careful when running rm
commands).
Solution 2:
No, there is no single command to do what you are asking.
Why?
This is the Unix philosophy: Write programs that do one thing and do it well. Write programs to work together.1
In this instance, the mkdir
and rm
commands do what you require, and work well together, since rm -r
will delete the directory as well, so a subsequent mkdir
will create the directory.
1The Art of Unix Programming, Eric S. Raymond, itself quoting Doug McIlroy.