在 shell 中自動切換使用 docker compose V1 跟 V2

docker compose v1 的指令是 docker-compose ,但如果安裝了 docker compose v2 會變成 docker compose ,而且兩者會同時存在。如果想要優先使用 docker compose v2,但在不存在時 fallback 回 docker compose v1,可以在 .bashrc 中設定這樣的 alias function:

dcp() {
    cmd=$(docker compose 2> /dev/null > /dev/null && echo "docker compose" || echo "docker-compose")
    $cmd $@
}

之後把 dcp 當成 docker compose 使用,會自動切換 docker compose v2 或 v1 風格的指令。

$ dcp up -d
[+] Running 5/0
 ⠿ Container my-super-project-unit-tester-1          Running                                                       0.0s
 ⠿ Container my-super-project-sql_db-1               Running                                                       0.0s
 ⠿ Container my-super-project-seeder-1               Running                                                       0.0s
 ⠿ Container my-super-project-web-service-1          Running                                                       0.0s
 ⠿ Container my-super-project-unit-tester-with-db-1  Running                                                       0.0s
$ dcp ps
NAME                                     COMMAND                  SERVICE               STATUS              PORTS
my-super-project-web-service-1           "/bin/sleep 999999999"   web-service           running
my-super-project-seeder-1                "/bin/sleep 999999999"   seeder                running
my-super-project-sql_db-1                "docker-entrypoint.s…"   sql_db                running             5432/tcp
my-super-project-unit-tester-1           "/bin/sleep 999999999"   unit-tester           running
my-super-project-unit-tester-with-db-1   "/bin/sleep 999999999"   unit-tester-with-db   running