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