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.shwithout any arguments, it will default to showing all folders (you can adjust this if needed, but it's a nice fallback). - Parameter Parsing: The
casestatement 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
doin 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
相关产品推荐
相关产品推荐

