How to Create A Directory in Bash if it does not exists

You can use the following script to create a directory like /home/user in a Bash script only if it does not already exist. This script checks if the directory exists, and if not, it creates it:

#!/bin/bash

# Define the directory path
DIR="/home/user"

# Check if the directory does not exist
if [ ! -d "$DIR" ]; then
    # Directory does not exist, so create it
    mkdir "$DIR"
    echo "Directory $DIR created."
else
    echo "Directory $DIR already exists."
fi

Here's what this script does:

  1. It defines the path of the directory you want to check and/or create (/home/user) in the DIR variable.
  2. The if [ ! -d "$DIR" ] command checks if the directory does not exist. The "!" (not or negate) operator negates the condition, so it becomes "if not directory".
  3. If the directory does not exist, mkdir "$DIR" creates the directory.
  4. The script then outputs a message indicating whether the directory was created or already existed.

To run this script:

  1. Save the script to a file, for example, create_directory.sh.
  2. Give it execute permissions with the command: chmod +x create_directory.sh.
  3. Run the script with ./create_directory.sh.

Remember to run the script with sufficient privileges. Creating a directory under /home/ may require sudo permissions, depending on your system's configuration.

Leave a Comment