If I am inside the path /parent/child1/child2 and I want to delete all the contents of parent whilst being in child2 except child1 from the parent. So can anyone tell me how will that command go?


Assuming that you're using the bash shell:

shopt -s dotglob extglob
rm -rf ../../!(child1)

The shopt command here is enabling two shell options in the bash shell. The first one, dotglob, makes sure that hidden names will be matched by filename globbing patterns. The second one, extglob, enables some extended globbing patterns (originally from the ksh shell).

The second line uses an extended globbing pattern to match all names in the parent directory, except for the child1 name. The contents of the parent directory is two levels above us, so we use ../../ first, and then add the pattern !(child1) which will match all names except the child1 name.

It passes all matching names to rm -rf for (recursive) deletion.

Instead of using a relative path in the ../../!(child1) pattern, you could also use the absolute path to the parent directory. According to your question, the absolute path is /parent, so the pattern then becomes /parent/!(child1) instead. Using the absolute path may be safer if you are unsure of where you actually are located relative to the parent directory.

Another obvious way to solve this is to move the child1 directory out of the way first, delete and recreate the parent directory, and then move the child1 directory into place again.

Here, I'm using absolute pathnames (using relative pathnames would be confusing as we are moving our current directory relative to parent):

mv /parent/child1 /tmp
rm -rf /parent
mkdir /parent
mv /tmp/child1 /parent

If you have GNU find, you can use this command

find ../.. -depth -not -path "../../child1/*" -not -samefile ../.. -not -samefile ../../child1 -exec rm -r {} \;

Just make sure you are really inside the /parent/child1/child2


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.