You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Bash脚本删除第二个参数指定目录的内容?

Hey there! Let's walk through how to build this Bash script safely—since deleting files is risky business, especially when you're starting out, we'll add safeguards to avoid accidental mishaps.

First, a quick clarification: your example call example.sh /home/A uses only one command-line argument (the directory path). You mentioned the "second parameter," but that doesn't align with the example. I'll cover both scenarios below, starting with the example you provided (using the first argument as the target directory).

1. Script to Delete All Contents of a Specified Directory

This script will take a directory path as input, validate it, ask for confirmation, then delete everything inside (including hidden files/directories) while leaving the directory itself intact.

#!/bin/bash

# Check if the user provided a directory argument
if [ $# -eq 0 ]; then
    echo "Oops! You need to specify a target directory."
    echo "Usage: $0 <target-directory>"
    exit 1
fi

TARGET_DIR="$1"

# Verify the target is a valid directory
if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: '$TARGET_DIR' isn't a valid directory."
    exit 1
fi

# Optional (but highly recommended): Confirm before deleting
read -p "Are you sure you want to erase ALL contents in '$TARGET_DIR'? (y/N) " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo "Deletion cancelled—phew!"
    exit 0
fi

# Enable dotglob to include hidden files/directories (excludes . and .. automatically)
shopt -s dotglob

# Delete all contents inside the target directory
rm -rf "$TARGET_DIR"/*

# Disable dotglob to reset default shell behavior
shopt -u dotglob

echo "Success! All contents in '$TARGET_DIR' have been deleted."

Key Details:

  • #!/bin/bash: Tells the system to use Bash to run the script.
  • $# -eq 0: Checks if no arguments were provided, then shows usage instructions.
  • [ ! -d "$TARGET_DIR" ]: Ensures the input path is actually a directory (avoids trying to delete a file by mistake).
  • The confirmation prompt: Prevents accidental deletion of critical directories (like / or your home folder).
  • shopt -s dotglob: Makes the * wildcard match hidden files/directories (like .bashrc or .config), which it normally ignores.
  • rm -rf "$TARGET_DIR"/*: Recursively (-r) and forcefully (-f) deletes everything inside the target directory. The /* ensures we only delete contents, not the directory itself.
2. If You Really Need the Second Argument

If your actual use case requires the target directory to be the second argument (e.g., example.sh some-flag /home/A), modify the script to check for two arguments and use $2 instead of $1:

#!/bin/bash

# Check for exactly two arguments
if [ $# -ne 2 ]; then
    echo "Error: You need to provide two arguments."
    echo "Usage: $0 <optional-flag> <target-directory>"
    exit 1
fi

TARGET_DIR="$2"

# Rest of the validation and deletion logic is identical to the script above
3. Script to Delete Only Files (Keep Subdirectories)

If you want to delete just the files in a directory (leaving all subdirectories and their contents intact), use one of these approaches:

Option 1: Use find (most reliable)

This deletes all regular files in the target directory (including hidden files) without touching subdirectories:

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 <target-directory>"
    exit 1
fi

TARGET_DIR="$1"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: '$TARGET_DIR' isn't a valid directory."
    exit 1
fi

read -p "Delete all files in '$TARGET_DIR' (keep subdirectories)? (y/N) " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

# Delete only files (not directories) in the target folder
find "$TARGET_DIR" -maxdepth 1 -type f -delete

echo "All files in '$TARGET_DIR' have been deleted."
  • -maxdepth 1: Ensures we don't recurse into subdirectories.
  • -type f: Only targets regular files.
  • -delete: Removes the matched files.

Option 2: Use rm (simpler for basic cases)

This works if you just want to delete visible and hidden files, leaving subdirectories:

shopt -s dotglob
rm -f "$TARGET_DIR"/*
shopt -u dotglob
  • -f: Force deletes files without prompting for confirmation.
Critical Safety Tips
  • Always test first: Replace rm -rf with echo rm -rf to see exactly what the script would delete before running it for real.
  • Quote your variables: Using "$TARGET_DIR" instead of $TARGET_DIR prevents errors if the directory path has spaces or special characters (e.g., /home/My Documents).
  • Avoid root directory deletion: Add a check to block deletion of / or system-critical folders:
    if [ "$TARGET_DIR" = "/" ]; then
        echo "Error: Cannot delete contents of root directory!"
        exit 1
    fi
    
  • Backup first: If you're working with important data, make a backup before testing any deletion scripts.

内容的提问来源于stack exchange,提问作者sergi martinez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:30:12