shell脚本中Switch的用法
时间: 2023-07-06 22:34:39 浏览: 298
在 Shell 脚本中,并没有像其他编程语言中的 Switch/Case 语句那样直接支持,但是可以使用其他的方式来实现相同的功能。其中较为常见的有以下两种方式:
1. if/elif 语句
使用 if/elif 语句可以很容易地实现 Switch/Case 的功能,示例代码如下:
```
#!/bin/bash
case "$1" in
start)
echo "Starting service..."
;;
stop)
echo "Stopping service..."
;;
restart)
echo "Restarting service..."
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac
```
上述脚本使用 case 语句来判断用户传入的参数,根据不同的参数执行不同的操作。如果用户传入的参数不是 start、stop 或 restart,则输出提示信息。
2. 数组和函数
另一种实现 Switch/Case 的方式是使用数组和函数,示例代码如下:
```
#!/bin/bash
actions=("start" "stop" "restart")
function start() {
echo "Starting service..."
}
function stop() {
echo "Stopping service..."
}
function restart() {
echo "Restarting service..."
}
for action in "${actions[@]}"; do
if [ "$1" == "$action" ]; then
"$action"
exit 0
fi
done
echo "Usage: $0 {start|stop|restart}"
exit 1
```
上述脚本将参数放入一个数组中,然后定义了三个函数分别对应不同的操作。脚本使用 for 循环遍历数组,如果用户传入的参数和数组中的某个元素相等,则调用对应的函数执行相应操作。如果用户传入的参数不是 start、stop 或 restart,则输出提示信息。
注意,上述两种方式都可以实现 Switch/Case 的功能,但第一种方式更为常用和简洁。
阅读全文
相关推荐


















