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 passesuserstostart_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.
- When you run
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
相关产品推荐
相关产品推荐

