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

Linux Shell脚本if条件实现:按品牌筛选文件夹列表

Solution for Brand-Specific Folder Listing

Hey there! Let's fix up your list.sh script to handle those brand-specific arguments properly. First off, your original script has a tiny syntax issue—you need a semicolon before do in the for loop. But beyond that, here's how to add the parameter handling logic you need:

Modified Script

#!/bin/bash

# Set default behavior to show all brands
target_brand="all"

# Parse command-line arguments
for arg in "$@"
do
    case "$arg" in
        --brand=*)
            # Extract the brand name after the equals sign
            target_brand="${arg#*=}"
            shift
            ;;
    esac
done

# Execute based on the target brand
if [ "$target_brand" = "all" ]; then
    # List all folders in files/data (the / ensures we only match directories)
    for d in files/data/*/; do
        echo "$d"
        # If you just want the folder name without the path, use: basename "$d"
    done
elif [ -d "files/data/$target_brand" ]; then
    # Check if the specified brand folder exists before outputting
    echo "files/data/$target_brand"
else
    # Optional: Error message if the brand doesn't exist
    echo "Error: Brand '$target_brand' doesn't exist in files/data/" >&2
    exit 1
fi

Key Improvements & Explanations

  • Default Behavior: If you run sh list.sh without any arguments, it will default to showing all folders (you can adjust this if needed, but it's a nice fallback).
  • Parameter Parsing: The case statement catches the --brand= argument, and we use bash parameter expansion ${arg#*=} to grab everything after the equals sign (this is a clean way to extract the brand name).
  • Directory Check: Before outputting a specific brand, we check if the folder actually exists with -d—this prevents the script from spitting out a non-existent path if someone mistypes a brand name.
  • Syntax Fix: Added the missing semicolon before do in the for loop (your original script would throw an error without this).

How to Test

  • To list only the apple folder:
    sh list.sh --brand=apple
    
  • To list all 100+ folders:
    sh list.sh --brand=all
    
  • If you test with a non-existent brand (e.g., --brand=google), you'll get a clear error message instead of empty output.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:10:11