What if directory already exists?

QuestionsQuestions8 SkillsProDec, 25 2025
0232

If you try to create a directory that already exists using the standard command, Linux will protect the existing directory and show you an error message.

1. The Default Behavior

If you run:

mkdir my_folder

And my_folder already exists, you will see this error:
mkdir: cannot create directory ‘my_folder’: File exists

Important: Your existing files inside that folder are safe. Linux will not overwrite or delete the content of the existing directory; it simply refuses to create a new one with the same name.

2. Using the -p flag (The "Silent" Way)

If you want to avoid getting that error message, you can use the -p flag:

mkdir -p my_folder

When you use -p:

  • If the directory exists, mkdir does nothing and returns no error.
  • If the directory does not exist, it creates it (and any parent directories needed).

This is very useful in automation scripts where you want to make sure a folder is there before doing work, but you don't want the script to crash if the folder was already created earlier.

Summary

  • Standard mkdir: Fails and tells you it exists.
  • mkdir -p: Stay silent and move on if it exists.

In both cases, your existing data remains untouched! Ready to try creating a folder twice to see the error?

0 Comments

no data
Be the first to share your comment!