运行脚本后,界面如下:
选择对应的编号后,会列举所有关闭的容器或者所有开启的容器列表,当我要启动一个容器 时输入1,就会出现下面的页面。
然后输入指定的编号后,就会启动对应的容器。
脚本代码如下:
#!/bin/bashfunction show_running_containers() {runningContainers=$(docker ps --format "table {{.ID}}\t{{.Names}}" | awk 'NR>1' | nl)echo "运行中的容器:"echo "$runningContainers"
}function show_stopped_containers() {stoppedContainers=$(docker ps -a --filter "status=exited" --format "table {{.ID}}\t{{.Names}}" | awk 'NR>1' | nl)echo "关闭的容器:"echo "$stoppedContainers"
}function start_container() {show_stopped_containersread -p "请输入要启动的容器编号(输入0退出): " userInputif [ "$userInput" -eq 0 ]; thenecho "退出脚本"elsecontainerId=$(docker ps -a --filter "status=exited" -q | sed -n "${userInput}p")if [ -n "$containerId" ]; thenecho "正在启动容器:$containerId"if docker start $containerId &> /dev/null; thenecho "容器启动成功"elseecho "容器启动失败,原因:$(docker inspect -f '{{.State.Status}}' $containerId)"fielseecho "输入无效,未找到对应编号的容器"fifi
}function stop_container() {show_running_containersread -p "请输入要关闭的容器编号(输入0退出): " userInputif [ "$userInput" -eq 0 ]; thenecho "退出脚本"elsecontainerId=$(docker ps -q | sed -n "${userInput}p")if [ -n "$containerId" ]; thenecho "正在关闭容器:$containerId"if docker stop $containerId &> /dev/null; thenecho "容器关闭成功"elseecho "容器关闭失败,原因:$(docker inspect -f '{{.State.Status}}' $containerId)"fielseecho "输入无效,未找到对应编号的容器"fifi
}function restart_container() {show_running_containersread -p "请输入要重启的容器编号(输入0退出): " userInputif [ "$userInput" -eq 0 ]; thenecho "退出脚本"elsecontainerId=$(docker ps -q | sed -n "${userInput}p")if [ -n "$containerId" ]; thenecho "正在重启容器:$containerId"if docker restart $containerId &> /dev/null; thenecho "容器重启成功"elseecho "容器重启失败,原因:$(docker inspect -f '{{.State.Status}}' $containerId)"fielseecho "输入无效,未找到对应编号的容器"fifi
}function force_delete_container() {show_running_containersread -p "请输入要强制删除的容器编号(输入0退出): " userInputif [ "$userInput" -eq 0 ]; thenecho "退出脚本"elsecontainerId=$(docker ps -q | sed -n "${userInput}p")if [ -n "$containerId" ]; thenecho "正在强制删除容器:$containerId"if docker rm -f $containerId &> /dev/null; thenecho "容器删除成功"elseecho "容器删除失败"fielseecho "输入无效,未找到对应编号的容器"fifi
}while true; doecho "请选择操作:"echo "1. 启动容器"echo "2. 关闭容器"echo "3. 重启容器"echo "4. 强制删除容器"echo "0. 退出"read -p "请输入操作编号: " choicecase $choice in1)start_container;;2)stop_container;;3)restart_container;;4)force_delete_container;;0)echo "退出脚本"break;;*)echo "输入无效,请重新输入";;esac
done
将代码写进一个sh文件。然后启动后,即可使用。
点点关注,点点赞呀。持续更新有用的知识................................................