shell习题-管理容器


用shell写一个脚本,实现一键管理docker容器,比如启动/关闭/删除容器等操作。

要求:

1 脚本支持启动全部容器、关闭全部容器、删除全部容器

2 需要提示用户如何使用该脚本,需给出范例

 

参考答案:

说明,本脚本为端亚同学提供。

#! /bin/bash

##start,restart,delete the docker containers
##written by zhdya_20171114
list=`docker ps -a |awk '{print $2}'| grep -v 'ID'`
echo "======================================="
echo -e "pls check the follow list of container: \n$list"
read -p "pls choose an action which you want!<1.start 2.stop 3.rm > " act
echo "======================================"
echo -e "stop\nstart\nrm\nrmi" > /tmp/docker.txt 
##judge if input the words or not!

if [ -z $act ]
then
        echo "you type was wrong,pls just input "start"."stop"."rm"."rmi"."
        exit
fi

##judge if input a wrong words!!
if grep -wq $act /tmp/docker.txt
then
        case $act in
        start)
                docker start $(docker ps -a | awk '{ print $1}' | tail -n +2)
                echo "already start all of container,pls checking it.."
        ;;

        stop)
                docker stop $(docker ps -a | awk '{ print $1}' | tail -n +2)
                echo "already restart all of container,pls checking it.."
        ;;

        rm)
                docker rm $(docker ps -a | awk '{ print $1}' | tail -n +2)
                echo "already rm all of container,pls checking it.."
        ;;

        *)
                docker rmi $(docker images | awk '{print $3}' |tail -n +2)
                echo "already rm all of container,pls checking it.."
        esac
else
        echo "you type was wrong,pls just input "start"."stop"."rm"."rmi"."
fi