In shell scripts, creating directories primarily uses the mkdir command. Below are the basic methods and several practical examples:
Basic Usage
The simplest command to create a directory is:
bashmkdir new_directory
This creates a new directory named new_directory in the current working directory.
Creating Multiple Directories
You can create multiple directories at once:
bashmkdir dir1 dir2 dir3
Creating Nested Directories
If you need to create multi-level directories, you can use the -p option:
bashmkdir -p dir1/dir2/dir3
This creates dir1, then dir2 within dir1, and finally dir3 within dir2. If parent directories already exist, the -p option will ignore them.
Example: Creating User Data Directories
Suppose you are writing a script that needs to create personal folders for multiple users under /data/users. You can write the script as follows:
bash#!/bin/bash # Assuming the user list is stored in an array users=("alice" "bob" "charlie") # Create the base directory base_dir="/data/users" mkdir -p "$base_dir" # Create directories for each user for user in "${users[@]}"; do mkdir "$base_dir/$user" -done
This script first ensures the base directory /data/users exists, then iterates over each username in the array to create individual directories.
Error Handling
When creating directories, you may encounter permission issues or other errors. Check the exit status of the mkdir command to handle errors:
bashmkdir new_directory if [ $? -ne 0 ]; then echo "Failed to create directory." exit 1 fi
This covers the basic methods and common use cases for creating directories in shell scripts. We hope these examples help you understand how to apply these commands in practical work.