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

Bash中Case语句传递参数:实现指定服务启停的方法

Got it, let's fix this up for you! The core issue here is that your current start case branch isn't passing the extra command-line arguments (like users) to your start_services function. Since you already built the function to handle specific services, we just need to forward those parameters along.

Modified Case Statement

Update your case block to pass all arguments after the first one to the corresponding function:

case "$1" in
    (-h)
        display_help
        exit 0
        ;;
    (start)
        # Pass all arguments starting from the 2nd one to start_services
        start_services "${@:2}"
        ;;
    (stop)
        # Optional: Do the same if stop_services needs to handle specific services
        stop_services "${@:2}"
        ;;
    (*)
        display_help
        exit 0
        ;;
esac

What's happening here?

  • ${@:2} is a shell parameter expansion that grabs all positional arguments starting from the 2nd one.
    • When you run ./services.sh start users, this passes users to start_services.
    • When you run ./services.sh start, ${@:2} is empty, so your function will fall back to its "start all services" logic exactly as you want.

Quick Check for Your Function

Just to confirm, your start_services function should be using $@ to access the passed service names, like this example:

start_services() {
    if [ $# -eq 0 ]; then
        echo "Starting all services..."
        # Logic to start every service
    else
        for service in "$@"; do
            echo "Starting service: $service..."
            # Logic to start the specific service
        done
    fi
}

This setup will work seamlessly for both your "start all" and "start specific service" use cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:11:12