3

Suppose I have a path

Leonardo/data/approach/tennis/video

and I want to delete approach directory, which means that path should look like this:

Leonardo/data/tennis/video

Can I do it from the terminal with some command?

Without copying tennis to data and then delete approach manually?

1
  • 4
    Just move it, instead of copying: mv Leonardo/data/approach/tennis Leonardo/data/
    – dadexix86
    Dec 20, 2015 at 16:08

2 Answers 2

2

You can use this function; it will move everything inside the directory passed as an argument one level above, hence taking care of multiple files / folders in the target directory:

function delete_dir() {
    [ -d "$1" ] || return;
    for x in "$1"/*; do
        mv -i "$x" "$1"/..
    done
    rmdir "$1"
}

Add it at the end of ~/.bashrc and run . ~/.bashrc in the running Bash instances (if any) to apply the changes immediately.

$ tree
.
└── foo
    └── bar
        ├── 1
        ├── 2
        └── 3

2 directories, 3 files
$ delete_dir foo/bar
$ tree
.
└── foo
    ├── 1
    ├── 2
    └── 3

1 directory, 3 files
1

With a simple:

mv Leonardo/data/approach/tennis Leonardo/data && rmdir Leonardo/data/approach

Why rmdir? In order to not delete the directory when subdirectories still exist.


Example

$ mkdir -p Leonardo/data/approach/tennis/video

$ tree                                                                                                                 
.
`-- Leonardo
    `-- data
        `-- approach
            `-- tennis
                `-- video


5 directories, 0 files

$ mv Leonardo/data/approach/tennis Leonardo/data && rmdir Leonardo/data/approach                                    

$  tree                                                                                                                 
.
`-- Leonardo
    `-- data
        `-- tennis
            `-- video

4 directories, 0 files
2
  • @kos OMG; I'm stupid
    – A.B.
    Dec 20, 2015 at 16:33
  • Nah, It happens to the best of us :)
    – kos
    Dec 20, 2015 at 16:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .