You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Bash脚本报错修复:无法解析elif子句及命令未找到问题

Fixing Your Bash Script for Moving Empty Files

Let's walk through fixing your script step by step, since there are a few syntax and logic issues causing those errors. First, here's the corrected, fully functional version of your script:

#!/bin/bash
# Script to move empty files from current directory into the subdirectory Empty_Files
# Usage: ./move_empty

subdirectory="Empty_Files"

# Check if the subdirectory exists; create it if not
if [ -d "$subdirectory" ]; then
    echo "$subdirectory exists!"
else
    mkdir -p "$subdirectory"
    echo "Empty_Files subdirectory created"
fi

# Find all non-hidden, regular empty files in the current directory
empty_files=$(find . -maxdepth 1 -type f ! -name ".*" -size 0)

# Check if there are any empty files
if [ -n "$empty_files" ]; then
    echo "Found empty files:"
    echo "$empty_files"
    echo -n "Would you like to move these files to $subdirectory? (Y/N): "
    read useranswer

    # Handle user input
    if [[ "$useranswer" =~ ^[Yy]$ ]]; then
        # Move each empty file (using xargs to handle spaces in filenames)
        echo "$empty_files" | xargs -I {} mv {} "$subdirectory/"
        echo "Successfully moved empty files to $subdirectory"
    elif [[ "$useranswer" =~ ^[Nn]$ ]]; then
        echo "No files were moved."
    else
        echo "Invalid input. Please enter Y or N."
        exit 1
    fi
else
    echo "No empty non-hidden files found in the current directory."
    exit 55
fi

Let's break down the fixes for your original errors:

  • Incorrect directory check: Your script used -f (for regular files) to verify the subdirectory exists—we replaced this with -d which properly checks for directories. We also removed the hardcoded path to make the script portable, using the $subdirectory variable instead.
  • Broken variable assignment: Bash doesn't use a $ when assigning variables, and piping ls into a variable is unreliable for filenames (especially those with spaces). We used find to safely locate non-hidden empty files instead.
  • Invalid condition syntax: Your if [ $useranswer = "y" || "Y" ] was wrong Bash syntax. We switched to [[ "$useranswer" =~ ^[Yy]$ ]] to cleanly match uppercase/lowercase Y, and added the missing then keyword to the elif clause (which caused your parsing error).
  • Wrong read syntax: read $useranswer should be read useranswer—you don't use $ when assigning input to a variable.
  • Logic flaws for multiple files: The original script didn't account for multiple empty files. Using find and xargs ensures we handle all empty files correctly, even those with spaces in names.
  • Improved flow: We moved the "no empty files" check to an else clause, making the logic more intuitive and eliminating messy nested conditionals.

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

火山引擎 最新活动